首页 > 后端开发 > Python教程 > 如何使用 Pandas 根据特定分隔符将文本字符串拆分为多行?

如何使用 Pandas 根据特定分隔符将文本字符串拆分为多行?

Barbara Streisand
发布: 2024-11-10 08:40:03
原创
427 人浏览过

How can I split text strings into multiple rows based on specific delimiters using Pandas?

Pandas 将文本拆分为多行的方法

问题:
大型 CSV 文件包含一列需要根据特定分隔符将文本字符串拆分为多行。目标是为每组分割文本创建单独的行。

使用 Pandas 的解决方案:

  1. 使用第一个分隔符(空格)分割文本str.split(' ').
  2. 应用 apply() 函数将列表中的每个字符串按秒分割分隔符(冒号)并将其转换为系列。
  3. 使用 stack() 将生成的 DataFrame 转换为单个列并重置索引。
  4. 将列重命名为“Seatblocks”。
  5. 从 DataFrame 中删除原始的“Seatblocks”列。
  6. 加入新列原始 DataFrame 的“Seatblocks”列。

按空格和冒号分割:

s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()
s.index = s.index.droplevel(-1)
s.name = 'Seatblocks'
del df['Seatblocks']
df.join(s)
登录后复制

示例输出:

   CustNum     CustomerName  ItemQty Item  ItemExt  Seatblocks
0    32363  McCartney, Paul        3  F04       60  2:218:10:4,6
1    31316     Lennon, John       25  F01      300  1:13:36:1,12
1    31316     Lennon, John       25  F01      300  1:13:37:1,13
登录后复制

分割冒号:

df.join(s.apply(lambda x: Series(x.split(':'))))
登录后复制

示例输出:

   CustNum     CustomerName  ItemQty Item  ItemExt  0    1   2     3
0    32363  McCartney, Paul        3  F04       60  2  218  10   4,6
1    31316     Lennon, John       25  F01      300  1   13  36  1,12
1    31316     Lennon, John       25  F01      300  1   13  37  1,13
登录后复制

以上是如何使用 Pandas 根据特定分隔符将文本字符串拆分为多行?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板