我一直在努力寻找小组之间的差异。因为它有点复杂,所以请在下面查看我的工作和代码:
import pandas as pd
df = {'Occ': ['Chef','Chef','Chef',
'Programmer','Programmer','Programmer','Data','Data','Data'],
'Skill': ['Cook', 'Budget','Communication','Python', 'R','Communication','R','Python','SAS']}
df = pd.DataFrame(data=df)
Occ Skill
Chef Cook
Chef Budget
Chef Communication
Programmer Python
Programmer R
Programmer Communication
Data R
Data Python
Data SAS
理想情况下,我需要找到每种可能的工作组合的尺寸之间的差异。我确实做了尝试,当我添加了第三个职业时,当我有两个职业时,它就起作用了,但是失败了。我所有的代码都在下面
Occ_s Occ_t Skill_missing
Chef Programmer Python
Chef Programmer R
Chef Data SAS
Chef Data R
Chef Data Python
Programmer Chef Cook
Programmer Chef Budget
Programmer Data SAS
Data Chef Cook
Data Chef Budget
Data Chef Chef
Data Programmer SAS
df['Num'] = 1
df1 = df.set_index(['Occ','Skill'])['Num'].unstack(fill_value=0)
out = df1.stack(0).reset_index()
iter_df = [[i,j] for i in out['Occ'].unique() for j in out['Occ'].unique() if i!=j]
iter_df = pd.DataFrame(iter_df, columns=['Occ_s', 'Occ_t'])
final = pd.merge(out,iter_df, left_on='Occ', right_on='Occ_s', how='left')
del final['Occ']
test_join = pd.merge(final, df, left_on=['Occ_t','Skill'], right_on=
['Occ','Skill'], how='outer')
test_join = test_join.dropna(subset=['Occ'])
test_join = test_join[test_join['Skill_indicator'] !=1]
del test_join['Occ']
test_join = test_join.rename(columns={0:'Skill_indicator'})
test_join = test_join[['Occ_s','Occ_t','Skill','Skill_indicator']]
答案 0 :(得分:1)
如果我对您的理解正确,那么它将起作用: 这段代码是您的:
import pandas as pd
import copy
df = {'Occ': ['Chef','Chef','Chef',
'Programmer','Programmer','Programmer','Data','Data','Data'],
'Skill': ['Cook', 'Budget','Communication','Python',
'R','Communication','R','Python','SAS']}
df = pd.DataFrame(data=df)
df = df.set_index(['Occ','Skill'])['Num'].unstack(fill_value=0)
out = df.stack(0).reset_index()
只需添加列名 out.columns = ['Occ','Skill','tmp']
创建out的副本。
out_2 = copy.deepcopy(out)
更改为零和零至一,以将Occ与另一个职业合并。因此,我们将获得一个表格,其中每个职业都将与另一个职业合并,而一个职业中的技能缺失。
out_2['tmp'] = 1- out_2['tmp']
只需添加列名。
out_2.columns =['Occ_t','Skill_t','tmp']
按计划合并
k= out_2.merge(out,on='tmp',how='inner')
但是,我们得到的每对[Occ,Skill]都将重复,且重复数为1,且为零,所以我们选择其中一个(我选择了0)。
k = k[k.tmp==0]
最后阶段,我们想获得不同的职业。并使用(k.Skill_t == k.Skill)获得所有Occ_t和Occ一项技能。
k[(k.Occ_t != k.Occ) & (k.Skill_t==k.Skill)][['Occ_t','Occ','Skill']]
结果:
Out[0]:
Occ_t Occ Skill
3 Chef Data Budget
6 Chef Programmer Budget
13 Chef Data Communication
23 Chef Data Cook
25 Chef Programmer Cook
27 Data Chef Python
37 Data Chef R
47 Data Chef SAS
53 Data Programmer SAS
58 Programmer Data Communication
63 Programmer Chef Python
73 Programmer Chef R