Pandas - 在 dataframe 的值中转置长度不相等的列表

4
这个问题是这个问题的扩展 Pandas: split list in column into multiple rows,现在我想合并更多的数据框。但我无法将其用于超过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

所以我做的是将列转换为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个回答

1

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

很酷,我认为它可以工作@Ken T,唯一的问题是我的数据框的第一列是一个列表,所以它的格式一直是[23] - 你知道为什么吗? - Mathias Lund
你是指“索引”列还是“职位”列? - Ken T
我是指工作职位,抱歉。 - Mathias Lund
@MathiasLund 我最好的猜测是该条目不是列表而是字符串,即 '[23]'。 - Ken T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接