【问题标题】:Partial string substitution in pandas seriespandas 系列中的部分字符串替换
【发布时间】:2018-02-03 01:38:55
【问题描述】:

我正在尝试在 pandas 数据框中进行字符串替换。需要遍历各个列,因此它基本上是一系列替换:

In [105]: df = pd.DataFrame([['0 - abc', 1, 5], ['0 - abc - xyz', 2, 3]], columns=['col1','col2','col3'])

In [106]: df
Out[106]:
            col1  col2  col3
0        0 - abc     1     5
1  0 - abc - xyz     2     3

In [107]: for col in df.columns:
     ...:     df[col] = df[col].replace(to_replace='".*"|^0', value=df['col3'], inplace=False, regex=True)
     ...:

In [108]: df
Out[108]:
   col1  col2  col3
0     5     1     5
1     3     2     3

我期望的结果不是上面的 df,而是:

In [110]: df_result
Out[110]:
            col1  col2  col3
0        5 - abc     1     5
1  3 - abc - xyz     2     3

也就是说,在 '0 - abc' 中,只有开头的 '0' 应该被替换为 '5' 而不是整个字符串。

我的正则表达式中缺少什么?有没有另一种方法可以在熊猫中完成这种字符串替换?谢谢。

【问题讨论】:

    标签: python regex pandas dataframe series


    【解决方案1】:

    使用.astypedf['col3'] 转换为str 可以解决您的问题:

    In [836]: df.iloc[:, 0].replace('^0', df['col3'].astype(str), regex=True)
    Out[836]: 
    0          5 - abc
    1    3 - abc - xyz
    Name: col1, dtype: object
    

    我也简化了您的正则表达式,尽管我不确定 100% 它是否适合您的所有用例:

    ^0
    

    这只会匹配前导零并替换它。您可以根据需要将其合并到您的代码中。

    【讨论】:

    • 感谢@COLDSPEED!是的,我的用例需要有'|' (OR) 正则表达式中的条件。
    • @D.prd 当然。根据需要进行修改。但主要修复是.astype
    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 2016-02-16
    • 2019-10-01
    • 2020-11-09
    • 2022-11-25
    • 2019-07-25
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多