这个问题是这个问题Pandas: split list in column into multiple rows的扩展,现在这次我想要合并更多的DataFrame.我无法使用超过2个dfs.
我有这个DataFrame:
Index Job positions Job types Locations
0 [5] [6] [3, 4, 5]
1 [1] [2, 6] [3, NaN]
2 [1,3] [9, 43] [1]
我想要每一个数字组合,所以最终的结果是:
index Job position Job type Location
0 5 6 3
0 5 6 4
0 5 6 5
1 1 2 3
1 1 2 NaN
1 1 6 3
1 1 6 NaN
2 1 9 1
2 1 43 1
2 3 9 1
2 3 43 1
所以我所做的就是将列转换为Series:
positions = df['Job positions'].apply(pd.Series).reset_index().melt(id_vars='index').dropna()[['index', 'value']].set_index('index')
types = df['Job types'].apply(pd.Series).reset_index().melt(id_vars='index').dropna()[['index', 'value']].set_index('index')
locations = df['Locations'].apply(pd.Series).reset_index().melt(id_vars='index').dropna()[['index', 'value']].set_index('index')
dfs = [positions, types, locations]
然后尝试将它们合并为:
df_final = reduce(lambda left,right: pd.merge(left,right,left_index=True, right_index=True, how="left"), dfs)
但似乎用NaN跳过了这些领域 – 我该如何防止这种情况发生?
解决方法:
1行:
import itertools
dfres = pd.DataFrame([(i[0],)+j for i in df.values for j in itertools.product(*i[1:])]
,columns=df.columns).set_index('index')
Job positions Job types Locations
index
0 5 6 3
0 5 6 4
0 5 6 5
1 1 2 3
1 1 2 NaN
1 1 6 3
1 1 6 NaN
2 1 9 1
2 1 43 1
2 3 9 1
2 3 43 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。