【问题标题】:Splitting a String in Pandas DF and Adding a Column with the Resulting List of Values在 Pandas DF 中拆分字符串并添加带有结果值列表的列
【发布时间】:2018-04-23 03:00:16
【问题描述】:

我正在尝试拆分 Pandas DF 中的字符串并将结果列表添加为新列。例如字符串:

"A;B;C;D"

将存储在新列中:

['A','B','C','D']

目前正在尝试此代码:

df['SplitList'] = [re.split(";",i) for i in df['List']]

但是得到这个错误:

File "C:\Python27\lib\re.py", line 171, in split
return _compile(pattern, flags).split(string, maxsplit)
TypeError: expected string or buffer

【问题讨论】:

  • 很酷,如果您有任何问题,请告诉我们。
  • 我添加了我得到澄清的错误。

标签: python regex string pandas split


【解决方案1】:

在 pandas 中,首选方法是使用 str 方法

df = pd.DataFrame({'col': ["A;B;C;D"]})
df['new'] = df['col'].str.split(';')

    col     new
0   A;B;C;D [A, B, C, D]

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 2014-08-13
    • 2020-01-31
    • 1970-01-01
    • 2018-10-02
    • 2018-01-15
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多