我有以下数据帧
import pandas as pd
df_occurencies = pd.DataFrame({'day':[1,2,3,4,5],
'occ':[['frog','wasp','bee'],
['frog','whale','barley','orchid'],
['orchid','barley','frog'],
['orchid','whale','frog'],
['orchid','barley','tulip']]})
df_kingdoms = pd.DataFrame({'item':['frog','wasp','bee',
'whale','barley','orchid',
'tulip'],
'kingdom':['animalia','animalia','animalia',
'animalia','plantae','plantae',
'plantae']})
我需要设置另一列,根据occ
值对df_kingdoms
列中的观察结果进行分类。
这些值都是异构的,因此所需的结果将是这样的:
day occ desired_result
0 1 [frog, wasp, bee] "animals"
1 2 [frog, whale, barley, orchid] "animals and plants"
2 3 [orchid, barley, frog] "mostly plants"
3 4 [orchid, whale, frog] "mostly animals"
4 5 [orchid, barley, tulip] "plants"
我知道有很多方法可以解决此问题,但我尝试使用许多.loc
定义的函数失败,但我认为这些函数甚至不值得发布。而且我需要在大型数据集上执行此操作,因此速度越快越好。
答案 0 :(得分:1)
这应该做:
dic_kd={i:j for i,j in zip(df_kingdoms.item,df_kingdoms.kingdom)}
desired_output=[]
for I in df_occurencies.occ:
list_aux=[dic_kd[i] for i in I]
if (list_aux.count('animalia')!=0) and (list_aux.count('plantae')==0) :
desired_output.append('animals')
elif (list_aux.count('animalia')==0) and (list_aux.count('plantae')!=0) :
desired_output.append('plants')
elif list_aux.count('animalia')>list_aux.count('plantae'):
desired_output.append('mostly animals')
elif list_aux.count('animalia')<list_aux.count('plantae'):
desired_output.append('mostly plants')
else:
desired_output.append('animals and plants')
df_occurencies['desired output']=desired_output
告诉我如果您什么都不懂,我会帮助您