Pandas 使用正则表达式有条件地更改单元格

Pandas conditionally change cells with regex

我有一个数据框,其中包含一些被解释为对象的单元格值,例如 $1,245。

我如何编写一个 lambda 函数来删除“$”和“,”并转换为仅在条目包含“$”的单元格中浮动?

我以前可以在没有 if-else 的情况下让它工作。但这也弄乱了其他没有 $ 的字符串列。

df = df.apply(lambda x: x.str.replace('[$,]', 
'').astype(float) if '$' in x else x)

示例数据:

Programmer, Hawaii,"5,887",",657",",229",.72
Engineering Manager, West Virginia,"5,420",",618",",220",.49
Data Scientist, Pennsylvania,"4,863",",572",",209",.22

更改 replace() 以将 regex=True 与原始 r 字符串一起使用,并将过滤器更改为测试 x.str.contains('[$,]').all():

df = (df.apply(lambda x:
    x.str.replace(r'[$,]', '', regex=True).astype(float)
    if x.str.contains('[$,]').all() else x))

#                      0               1         2       3       4      5
# 0           Programmer          Hawaii  115887.0  9657.0  2229.0  55.72
# 1  Engineering Manager   West Virginia  115420.0  9618.0  2220.0  55.49
# 2       Data Scientist    Pennsylvania  114863.0  9572.0  2209.0  55.22

您还可以 applymap() 通过链接 2x replace():

df = df.applymap(lambda x: float(x.replace('$', '').replace(',', '')) if '$' in x else x)