gpt4 book ai didi

python - 解压 DataFrame 的列表元素

转载 作者:行者123 更新时间:2023-11-28 22:35:36 25 4
gpt4 key购买 nike

我有这个 df:

l1 = ['a', 'b', 'c']
l2 = ['x', ['y1', 'y2', 'y3'], 'z']
df = pd.DataFrame(list(zip(l1, l2)), columns = ['l1', 'l2'])

结果:

  l1            l2
0 a x
1 b [y1, y2, y3]
2 c z

我需要的是解压 l2 中的内部列表并像这样在 l1 中传播相应的值:

  l1  l2
0 a x
1 b y1
2 b y2
3 b y3
4 c z

执行此操作的正确方法是什么?谢谢。

最佳答案

您可以使用 itertools.zip_longest 的嵌套列表推导式.

import pandas as pd

from itertools import zip_longest

l1 = ['a', 'b', 'c']
l2 = ['x', ['y1', 'y2', 'y3'], 'z']

expanded = [(left, right) for outer in zip(l1, l2)
for left, right in zip_longest(*outer, fillvalue=outer[0])]

pd.DataFrame(expanded)

结果是……

   0   1
0 a x
1 b y1
2 b y2
3 b y3
4 c z

对我来说,这是列表组合太长的边缘。还假定 l1 中没有列表并将进行填充。

关于python - 解压 DataFrame 的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38078029/

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