kev*_*vin 20 python python-2.7 pandas
我在pandas dataframe中有以下数据:
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
Run Code Online (Sandbox Code Playgroud)
我想用三列(第1,第2,第3)执行一些简单的分析(例如,sum,groupby),但这三列的数据类型是object(或string).
所以我使用以下代码进行数据转换:
data = data.convert_objects(convert_numeric=True)
Run Code Online (Sandbox Code Playgroud)
但是,由于美元符号,转换可能不起作用.有什么建议吗?
dag*_*rha 39
@ EdChum的答案很聪明,效果很好.但是,因为烘烤蛋糕的方法不止一种....为什么不使用正则表达式呢?例如:
df[df.columns[1:]].replace('[\$,]', '', regex=True).astype(float)
Run Code Online (Sandbox Code Playgroud)
对我来说,这有点可读性.
您也可以使用locale如下
import locale
import pandas as pd
locale.setlocale(locale.LC_ALL,'')
df['1st']=df.1st.map(lambda x: locale.atof(x.strip('$')))
Run Code Online (Sandbox Code Playgroud)
注意上面的代码是在 Python 3 和 Windows 环境下测试的
小智 8
要转换为整数,请使用:
carSales["Price"] = carSales["Price"].replace("[$,]", "", regex=True).astype(int)
Run Code Online (Sandbox Code Playgroud)
您可以使用矢量化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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
其它的办法:
In [108]:
df[df.columns[1:]] = df[df.columns[1:]].apply(lambda x: x.str[1:].str.split(',').str.join('')).astype(np.int64)
df
Out[108]:
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
Run Code Online (Sandbox Code Playgroud)
您可以使用该方法str.replace和正则表达式'\D'删除所有非数字字符或'[^-.0-9]'保留减号、小数点和数字:
for col in df.columns[1:]:
df[col] = pd.to_numeric(df[col].str.replace('[^-.0-9]', ''))
Run Code Online (Sandbox Code Playgroud)