gpt4 book ai didi

python - 使用 str.split (panda) 拆分一列时强制列数

转载 作者:行者123 更新时间:2023-11-28 20:58:50 25 4
gpt4 key购买 nike

我不知道这个过程是否可以用 str.split。但是例如,我在数据框 df 中有以下列:

   Column
0 a-b-c-d-e-f-g-h-i-j
1 a-a-b-b-c-c
2 a-a-b-b

我知道如果我这样做

df['Column'].str.split('-', expand=True)

然后我会得到如下结果:

  0  1  2  3  4      5      6      7      8      9
0 a b c d e f g h i j
1 a a b b c c None None None None
2 a a b b None None None None None None

当拆分完成时,它根据元素的最大数量创建多个列。

我想知道是否有可能总是有 10 列,而不管元素的数量如何,只要它在 0 到 10 之间,并像这里一样用“无”填充剩余的列。

所以会变成以下列的东西:

       Column
0 a-b-c-d-e-f-g-h
1 a-a-b-b-c-c
2 a-a-b-b

进入:

  0  1  2  3  4      5      6      7      8      9
0 a b c d e f g h None None
1 a a b b c c None None None None
2 a a b b None None None None None None

最佳答案

reindex 之后
通过改进实现 user3483203

df.Column.str.split('-', expand=True).reindex(columns=range(10))

0 1 2 3 4 5 6 7 8 9
0 a b c d e f g h i j
1 a a b b c c None None None None
2 a a b b None None None None None None

理解方法

pd.DataFrame([
(lambda l: l + [None] * (10 - len(l)))(x.split('-'))
for x in df.Column
], df.index)

0 1 2 3 4 5 6 7 8 9
0 a b c d e f g h None None
1 a a b b c c None None None None
2 a a b b None None None None None None

关于python - 使用 str.split (panda) 拆分一列时强制列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51090026/

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