如何将带有值列表的列转换为Pandas DataFrame中的行 [英] How to convert column with list of values into rows in Pandas DataFrame

查看:269
本文介绍了如何将带有值列表的列转换为Pandas DataFrame中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

Hi I have a dataframe like this:

    A             B 
0:  some value    [[L1, L2]]

我想将其更改为:

    A             B 
0:  some value    L1
1:  some value    L2

我该怎么办?

推荐答案

您可以这样操作:

In [84]: df
Out[84]:
               A               B
0     some value      [[L1, L2]]
1  another value  [[L3, L4, L5]]

In [85]: (df['B'].apply(lambda x: pd.Series(x[0]))
   ....:         .stack()
   ....:         .reset_index(level=1, drop=True)
   ....:         .to_frame('B')
   ....:         .join(df[['A']], how='left')
   ....: )
Out[85]:
    B              A
0  L1     some value
0  L2     some value
1  L3  another value
1  L4  another value
1  L5  another value

更新: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆