在Pandas中替换逗号和点号

7
我有一个数据列,格式为3.4500,00欧元。现在我想将其与另一列浮点数(如4000.00)进行比较。我应该如何处理这个字符串,移除"EUR"并将逗号替换为小数点,然后将其转化为浮点数以便能够进行比较?

1
你可以使用 .replace() - Mario
1
你目前尝试了什么? - shaik moeed
2个回答

13

您可以使用正则表达式使您的条件更加通用,这将在 所有 情况下起作用:

# Make example dataframe for showing answer
df = pd.DataFrame({'Value':['3.4500,00 EUR', '88.782,21 DOLLAR']})

              Value
0     3.4500,00 EUR
1  88.782,21 DOLLAR

使用正则表达式,结合 str.replace 方法:

df['Value'].str.replace('[A-Za-z]', '').str.replace(',', '.').astype(float)

0    34500.00
1    88782.21
Name: Value, dtype: float64

解释:

  • str.replace('[A-Za-z\.]', '') 移除所有字母和点号。
  • str.replace(',', '.') 用点号替换逗号。
  • astype(float) 将对象(字符串)类型转换为浮点数。

0
这是我的解决方案:
模拟数据:
         amount     amount2
0   3.4500,00EUR    4000
1   3.600,00EUR     500

使用apply()函数,然后将数据类型转换为浮点型。
data['amount'] = data['amount'].apply(lambda x: x.replace('EUR', '')).apply(lambda x: x.replace('.', '')).apply(lambda x: x.replace(',', '.')).astype('float')

结果:

    amount    amount2
0   34500.0     4000
1   3600.0      500

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接