【发布时间】:2018-10-22 17:34:55
【问题描述】:
这个问题是这个问题Pandas: split list in column into multiple rows的延伸,现在我不想合并更多的DataFrames。而且我无法让它与超过 2 个 dfs 一起工作。
我有这个数据框:
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
所以我所做的就是将列转换为系列:
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 的字段 - 我该如何防止这种情况?
【问题讨论】: