【问题标题】:converting currency with $ to numbers in Python pandas在 Python pandas 中将带有 $ 的货币转换为数字
【发布时间】:2015-12-04 12:30:36
【问题描述】:

我在熊猫数据框中有以下数据:

    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

我想用三列(1st、2nd、3rd)执行一些简单的分析(例如 sum、groupby),但是这三列的数据类型是对象(或字符串)。

所以我使用以下代码进行数据转换:

data = data.convert_objects(convert_numeric=True)

但是,转换不起作用,也许是因为美元符号。有什么建议吗?

【问题讨论】:

标签: python python-2.7 pandas


【解决方案1】:

您可以使用矢量化的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

另一种方式:

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

【讨论】:

    【解决方案2】:

    @EdChum 的回答很聪明,效果很好。但既然烤蛋糕的方法不止一种……为什么不使用正则表达式呢?例如:

    df[df.columns[1:]] = df[df.columns[1:]].replace('[\$,]', '', regex=True).astype(float)
    

    对我来说,这更具可读性。

    【讨论】:

    • 更通用的做法是替换所有非数字字符,所以正则表达式为'\D'。请注意,这也会删除小数点,因此仅适用于整数值。要删除除数字和小数点以外的所有字符,您可以使用'[^.0-9]'
    • 现在是 2019 年,仍然没有更好的方法将货币系列转换为数字系列:/
    【解决方案3】:

    你也可以使用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 环境下测试的

    【讨论】:

      【解决方案4】:

      要转换为整数,请使用:

      carSales["Price"] = carSales["Price"].replace("[$,]", "", regex=True).astype(int)
      

      【讨论】:

      • 您好,请避免发布输出图像,此输出可能是文本格式。
      • 如果你把小数点换掉,你将拥有一辆 50 万美元的本田
      【解决方案5】:

      您可以使用方法str.replace 和正则表达式'\D' 删除所有非数字字符或使用'[^.0-9]' 保留数字和小数点:

      for col in df.columns[1:]:
          df[col] = pd.to_numeric(df[col].str.replace('[^.0-9]', ''))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        • 1970-01-01
        相关资源
        最近更新 更多