将带有$的货币转换为Python格式的数字
我在熊猫数据框中有以下数据:将带有$的货币转换为Python格式的数字,python,python-2.7,pandas,Python,Python 2.7,Pandas,我在熊猫数据框中有以下数据: state 1st 2nd 3rd 0 California $11,593,820 $109,264,246 $8,496,273 1 New York $10,861,680 $45,336,041 $6,317,300 2 Florida $7,942,848 $69,369,589 $4,697,244 3 Texas $7,536
state 1st 2nd 3rd
0 California $11,593,820 $109,264,246 $8,496,273
1 New York $10,861,680 $45,336,041 $6,317,300
2 Florida $7,942,848 $69,369,589 $4,697,244
3 Texas $7,536,817 $61,830,712 $5,736,941
我想用三列(第一列、第二列、第三列)执行一些简单的分析(例如sum、groupby),但这三列的数据类型是object(或string)
因此,我使用以下代码进行数据转换:
data = data.convert_objects(convert_numeric=True)
但是,可能由于美元符号,转换不起作用。有什么建议吗?您可以使用矢量化的
str
方法替换不需要的字符,然后将类型强制转换为int:
In [81]:
df[df.columns[1:]] = df[df.columns[1:]].apply(lambda x: x.str.replace('$','')).apply(lambda x: x.str.replace(',','')).astype(np.int64)
df
Out[81]:
state 1st 2nd 3rd
index
0 California 11593820 109264246 8496273
1 New York 10861680 45336041 6317300
2 Florida 7942848 69369589 4697244
3 Texas 7536817 61830712 5736941
dtype
更改现已确认:
In [82]:
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 4 entries, 0 to 3
Data columns (total 4 columns):
state 4 non-null object
1st 4 non-null int64
2nd 4 non-null int64
3rd 4 non-null int64
dtypes: int64(3), object(1)
memory usage: 160.0+ bytes
@埃德彻姆的回答很聪明,效果也很好。但既然烤蛋糕的方法不止一种。。。。为什么不使用正则表达式呢?例如:
df[df.columns[1:]] = df[df.columns[1:]].replace('[\$,]', '', regex=True).astype(float)
对我来说,这更具可读性。您还可以使用
locale
,如下所示
import locale
import pandas as pd
locale.setlocale(locale.LC_ALL,'')
df['1st']=df.1st.map(lambda x: locale.atof(x.strip('$')))
注意:上面的代码是在Python 3和Windows环境中测试的,只需使用下面简单高效的可读方法即可将其转换为整数
carSales["Price"] = carSales["Price"].replace('[\$\,\.]',"",regex=True).astype(int)
输出:
对于正则表达式解决方案,检查一个更通用的方法是替换所有非数字字符,因此正则表达式是
'\D'
。请注意,这也会删除小数点,因此仅适用于整数值。要删除除数字和小数点以外的所有字符,您可以使用'[^.0-9]'
。现在是2019年,仍然没有更好的方法将货币序列转换为数字序列:/Hi,请避免发布输出图像,此输出可能是文本格式。
carSales["Price"] = carSales["Price"].replace('[\$\,\.]',"",regex=True).astype(int)