首页 > 解决方案 > 从嵌入列中的列表中提取元素

问题描述

我有以下数据框:

col1   col2
[12, 2]  4
[2, 5]  3

我要这个:

col1A   col1B   col2
12        2       4
2        5       3

这个问题与类似,但在执行 df['col1'].str[0]时,我将其作为输出:

col1   col2
[       4
[       3

标签: pythonpandas

解决方案


采用:

new_df=df.T.apply(lambda x: x.explode()).T
print(new_df)
  col1 col1 col2
0   12    2    4
1    2    5    3

如果要重命名列,请使用:

df2=df.T.apply(lambda x: x.explode())
groups=df2.groupby(level=0)
letters=groups.cumcount().map({0:'A',1:'B'})
df2.index=(df2.index+letters).where(groups.size()>1,df2.index.to_series())
new_df=df2.T
print(new_df)

  col1A col1B col2
0    12     2    4
1     2     5    3

推荐阅读