展开组合上的列表列,并保留其他d

2024-10-03 02:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

How to unnest (explode) a column in a pandas DataFrame?

我相信这个问题与上面列出的问题不同。我试图找到一列中单元格的组合,并由此创建两列。上面的说明显示了如何取消嵌套列表,但不查找该列表的组合…

我有一个数据框,其中一列包含一个列表。我试图扩展这个数据框,这样我就可以得到列表的每一个组合,并且仍然保留其他信息。很难解释,下面是示例数据帧:

name    number    ID           code
1111      2        3    ['%AB','$12','&FD']

我试图找出如何将此数据帧转换为以下内容:

name    number    ID    to    from
1111      2        3    %AB    $12
1111      2        3    %AB    &FD
1111      2        3    $12    &FD

我试过的代码:

a = [y for x in df[['code']].stack() for y in combinations(x,2)]
df[['to','from']] = a

Tags: to数据nameinfromidnumberdf
1条回答
网友
1楼 · 发布于 2024-10-03 02:31:50

想法是为新数据帧中的索引向元组添加索引(^{}表示提取列),所以可能是^{}原始DataFrame

#if not default indices, create them
#df = df.reset_index(drop=True)

print (df)
   name  number  ID                    code
0  1111       2   3     ['%AB','$12','&FD']
1  1000       2   3  ['%AB1','$121','&FD1']


a = [(i,) + y for i, x in df.pop('code').items() for y in combinations(x,2)]
df1 = pd.DataFrame(a, columns=['idx','to','to']).set_index('idx')
print (df1)
       to    to
idx            
0     %AB   $12
0     %AB   &FD
0     $12   &FD
1    %AB1  $121
1    %AB1  &FD1
1    $121  &FD1

df2 = df1.join(df).reset_index(drop=True)
print (df2)
     to    to  name  number  ID
0   %AB   $12  1111       2   3
1   %AB   &FD  1111       2   3
2   $12   &FD  1111       2   3
3  %AB1  $121  1000       2   3
4  %AB1  &FD1  1000       2   3
5  $121  &FD1  1000       2   3

相关问题 更多 >