您可以看到,我的df包含一个价格清单,其中包含$106.00
和'1,190.00
的值。我想把这些值变成一个数值。我要替换$符号。但这行不通。
df = pd.DataFrame({'id':['A', 'B', 'C', 'D', 'E'], 'price':['$106.00', '$156.00',
'$166.00', '$106.00', '1,190.00']})
df['price'] = pd.to_numeric(df.price.str.replace("$",""))
# df['price'] = pd.to_numeric(df.price.str[1:])
# that givs me a ValueError: Unable to parse string "1,925.00" at position 7765
我想要的结尾
ID price
A 106.00
B 156.00
C 166.00
D 106.00
E 1,190.00
您可以使用regex
并将'$'
和','
替换为''
,然后转换为以下数字:(我们使用'|'
搜索$
或,
)
>>> df.price = pd.to_numeric(df.price.str.replace(r"$|,","", regex=True))
>>> df
id price
0 A 106.0
1 B 156.0
2 C 166.0
3 D 106.0
4 E 1190.0
试试这样。使用正则表达式将所有非数字值替换为",然后将其转换为十进制。对'price' list中的所有值应用
import pandas as pd
from re import sub
from decimal import Decimal
df = pd.DataFrame({'id':['A', 'B', 'C', 'D', 'E'], 'price':['$106.00', '$156.00',
'$166.00', '$106.00', '1,190.00']})
df['price']=df['price'].apply(lambda x: Decimal(sub(r'[^d.]', '', x)))
print(df)
输出id price
0 A 106.00
1 B 156.00
2 C 166.00
3 D 106.00
4 E 1190.00