gpt4 book ai didi

python - 将包含列表的列拆分为 Pandas 中的不同行

转载 作者:行者123 更新时间:2023-12-05 00:47:51 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to explode a list inside a Dataframe cell into separate rows

(12 个回答)


2年前关闭。




我在 Pandas 中有一个这样的数据框:

id     info
1 [1,2]
2 [3]
3 []

我想把它分成不同的行,如下所示:
id     info
1 1
1 2
2 3
3 NaN

我怎样才能做到这一点?

最佳答案

你可以试试这个:

>>> import pandas as pd
>>> df = pd.DataFrame({'id': [1,2,3], 'info': [[1,2],[3],[]]})
>>> s = df.apply(lambda x: pd.Series(x['info']), axis=1).stack().reset_index(level=1, drop=True)
>>> s.name = 'info'
>>> df2 = df.drop('info', axis=1).join(s)
>>> df2['info'] = pd.Series(df2['info'], dtype=object)
>>> df2
id info
0 1 1
0 1 2
1 2 3
2 3 NaN

类似问题发布在 here

关于python - 将包含列表的列拆分为 Pandas 中的不同行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50729552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com