【问题标题】:Split pandas Series rows containing multiline strings into separate rows将包含多行字符串的 pandas Series 行拆分为单独的行
【发布时间】:2014-11-26 17:14:45
【问题描述】:

我有一个熊猫系列,里面充满了这样的字符串:

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.]

但这只会破坏行内的字符串,而不是为每个标记分成自己的行。

【问题讨论】:

    标签: python pandas split series


    【解决方案1】:

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

    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')])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 2016-12-31
      • 2021-10-24
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      相关资源
      最近更新 更多