【问题标题】:How to use re.search column in dataframe如何在数据框中使用 re.search 列
【发布时间】:2018-08-30 14:51:21
【问题描述】:

此代码适用于单个字符串 (inputx),但当我将其替换为数据框中列的名称时,我无法让它工作。我想要做的是拆分 DESC 列中的字符串,其中大写单词(在字符串的开头)放置到列 break2 中,而描述的其余部分放置在列 break3 中。任何帮助表示赞赏。谢谢。

示例: What I want output to look like (but with the different DESC from each row

适用于硬编码字符串的代码:

inputx= "STOCK RECORD INQUIRY This is a system that keeps track of the positions, location and ownership of the securities that the broker holds"
pos = re.search("[a-z]", inputx[::1]).start()
Before_df['break1'] = pos
Before_df['break2'] = inputx[:(pos-1)]
Before_df['break3'] = inputx[(pos-1):]

但如果我用数据框列替换,我会收到错误消息:TypeError: expected string or bytes-like object

inputx = Before_df['DESC']
pos = re.search("[a-z]", inputx[::1]).start()
Before_df['break1'] = pos
Before_df['break2'] = inputx[:(pos-1)]
Before_df['break3'] = inputx[(pos-1):]

【问题讨论】:

  • 你看过 df.apply() 吗?
  • 我没有调查过这个。我不知道如何使用它,但会检查一下。

标签: python regex dataframe


【解决方案1】:

您可以在 df.str.split 方法中使用正则表达式

df[['result','result2','result3']] = df['yourcol'].str.split("([a-z])", expand= True)

如果你绝对必须使用 re.search(这听起来有点像家庭作业......)

for i in df.index:
    df.at[i, 'columnName'] = re.search("[a-z]", df.at[i, 'inputColumn'][::1]).start()

循环而不是使用df.apply() 的原因是因为数据帧不喜欢在应用期间被更改

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 2019-12-13
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    相关资源
    最近更新 更多