python - 将包含多行字符串的 Pandas 系列行拆分为单独的行

标签 python pandas split series

我有一个 pandas 系列,里面装满了这样的字符串:

In:    
s = pd.Series(['This is a single line.', 'This is another one.', 'This is a string\nwith more than one line.'])

Out:
0                        This is a single line.
1                          This is another one.
2    This is a string\nwith more than one line.
dtype: object

如何将此系列中包含换行符 \n 的所有行拆分为它们自己的行?我期望的是:

0      This is a single line.
1        This is another one.
2            This is a string
3    with more than one line.
dtype: object

我知道我可以用换行符分隔每一行

s = s.str.split('\n')

给出

0                        [This is a single line.]
1                          [This is another one.]
2    [This is a string, with more than one line.]

但这只会将行内的字符串打断,不会为每个标记打断它们自己的行。

最佳答案

您可以遍历每一行中的每个字符串以创建一个新系列:

pd.Series([j for i in s.str.split('\n') for j in i])

在输入上执行此操作比创建临时系列更有意义,例如:

strings = ['This is a single line.', 'This is another one.', 'This is a string\nwith more than one line.']
pd.Series([j for i in strings for j in i.split('\n')])

关于python - 将包含多行字符串的 Pandas 系列行拆分为单独的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27155129/

相关文章:

bash - 将 GNU Parallel 与 Split 结合使用

python - Kivy 日期选择器小工具

python - Flask Redis 队列 (RQ) worker 无法导入名为 app 的模块

python - pandas DataFrame 中列的更短符号

python - Pandas - 如何对 value_counts 进行切片?

python - Pandas 没有附加数据框

javascript - 将字符串拆分为 n 长度的数组

带冒号的 Java SPLIT : and xml

python - 在以下 python for 循环中需要这么长时间

python - 如何使用tesseract从图像的特定坐标提取文本?