python - Pandas DataFrame 中字符串的条件编辑

标签 python regex pandas

我正在学习 Pandas,并且有一个字符串 DataFrame,看起来有点像这样:

df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B'])
df
    A       B
0   Apple   Med6g7867
1   Orange  Med7g8976
2   Banana  Signal
3   Peach   Med8g8989
4   Mango   Possible result %gggyy

注意 B 列有两种类型的值,要么是 MedXgXXXX 形式的唯一标识符,要么是描述性字符串。我想做两件相关的事情。

  1. 将 B 的所有值替换为 NaN 的唯一标识符
  2. 保留描述性字符串,但截断任何带有 % 符号的字符串,以便仅保留 % 符号之前的字符串。

我想要一个这样的表格:

    A       B
0   Apple   NaN
1   Orange  NaN
2   Banana  Signal
3   Peach   NaN
4   Mango   Possible result

目前我可以像这样对表进行子集化:

df[df['B'].str.contains("Med")]
df[df['B'].str.contains("%")]

但我尝试没有实现 replace() 来允许我执行此操作。

感谢任何帮助。

最佳答案

import pandas as pd
df = pd.DataFrame([['Apple', 'Med6g7867'],
                   ['Orange', 'Med7g8976'],
                   ['Banana', 'Signal'],
                   ['Peach', 'Med8g8989'],
                   ['Mango', 'Possible result %gggyy']],
                  columns=['A', 'B'])

df['B'] = df['B'].str.extract(r'(?:^Med.g.{4})|([^%]+)', expand=False)
print(df)

产量

        A                 B
0   Apple               NaN
1  Orange               NaN
2  Banana            Signal
3   Peach               NaN
4   Mango  Possible result 

正则表达式模式具有以下含义:

(?:            # start a non-capturing group
  ^            # match the start of the string
  Med          # match the literal string Med
  .            # followed by any character
  g            # a literal g
  .{4}         # followed by any 4 characters
)              # end the non-capturing group
|              # OR
(              # start a capturing group
  [^%]+        # 1-or-more of any characters except %
)              # end capturing group

如果 B 列中的值以以下形式的唯一标识符开头 MedXgXXXX 则将匹配非捕获组。由于str.extract 只返回捕获组的值,即 Series 返回的值 str.extract 在此位置将有一个 NaN

如果捕获组匹配,则 str.extract 将返回 匹配值。

关于python - Pandas DataFrame 中字符串的条件编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189794/

相关文章:

javascript - 正则表达式:将标题 =""添加到 <img> 标签,但如果 <img> 位于 &lt;script&gt; 标签之间,则不添加标题 0x104567910

javascript - 正则表达式捕获标签

python-3.x - pandas read_csv 内存消耗

pandas - 导出到 csv 时的 timedelta 格式松散 - 有解决方案吗?

python - re.Pattern.findall 工作错误

python celery max-tasks-per-child-setting 默认值

OSX 10.8.1 上的 python 成像

regex - 检查字符串是否以 CMake 中的名称结尾

python - Pandas 按条件按列值分组

python - 段错误 : 11 python after upgrading to OS Big Sur