从列中嵌入的列表中提取元素

时间:2019-11-17 02:00:06

标签: python pandas

我有以下数据框:

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

我想要这个:

col1A   col1B   col2
12        2       4
2        5       3

这个问题类似于this,但是在做df['col1'].str[0]时,我得到的是输出:

col1   col2
[       4
[       3

2 个答案:

答案 0 :(得分:2)

使用:

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

答案 1 :(得分:1)

我会做

df=pd.DataFrame(df.pop('col1').tolist(),index=df.index).join(df)
Out[41]: 
    0   1  col2
0   1   2     1
1  10  11     2