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

标签 python python-3.x pandas

我不知道这个过程是否可以用 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/

相关文章:

Python - 从没有 numPy 的矩阵中删除列

python - Pandas 合并而不复制列

python - 如何创建 3x3 矩阵?

python - 将多索引排序到全深度( Pandas )

python - 使用 Pandas 将列值聚合到序列中

Python导入错误: No module named <myPackage>

python - 计算用户 session 数,定义为时间间隔

mysql - 当在 python 中插入多个数据帧时,没有从 mysql 获取值

python - 从列表中的字典中删除空值的有效方法是什么?

python - 如何在Python中仅读取存储在大csv文件中的数据片段