简体   繁体   English

将Pandas Dataframe转换为以逗号浮动时出错

[英]Error Converting Pandas Dataframe to float with comma

so I got a Dataframe with at least 2-3 columns with numbers running from 1 to 3000, and the numbers have comma. 所以我得到一个至少2-3列的数据帧,数字从1到3000,数字有逗号。 I need to convert the numbers to float or int in all the relevant columns.this is an example for my Dataframe: 我需要在所有相关列中将数字转换为float或int。这是我的Dataframe的一个示例:

data = pd.read_csv('exampleData.csv')
data.head(10)
 Out[179]:
 Rank     Total
  1         2
  20        40
  1,200    1,400
  NaN       NaN

as you can see from the example, my Dataframe consists of numbers, numbers with comma and some NaNs.I've read several posts here about converting to float or int, but I always get error messages such as: 'str' object has no attribute 'astype'. 从示例中可以看出,我的Dataframe由数字,带逗号的数字和一些NaN组成。我在这里读了几篇关于转换为float或int的帖子,但我总是收到错误消息,例如:'str'对象没有属性'astype'。 my approach is as follows for several columns: 我的方法如下几列:

cols = ['Rank', 'Total']
data[cols] = data[cols].apply(lambda x: pd.to_numeric(x.astype(str)
                                               .str.replace(',',''), errors='coerce'))

使用参数thousands

pd.read_csv('exampleData.csv', thousands=',')

John's solution won't work for numbers with multiple commas, like 1,384,496. John的解决方案不适用于带有多个逗号的数字,例如1,384,496。

A more scalable solution would be to just do 一个更具可扩展性的解决方案就是这样做

data = data.replace({",":""}, regex=True)

Then convert the strings to numeric. 然后将字符串转换为数字。

Pandas read_csv() takes many arguments which allow you to control how fields are converted. Pandas read_csv()接受许多参数,允许您控制字段的转换方式。 From the documentation : 文档

decimal : str, default ‘.’
    Character to recognize as decimal point (e.g. use ‘,’ for European data).

So, here's a crazy idea: convert the numerical fields using the keyword argument, "decimal = ',' ". 所以,这是一个疯狂的想法:使用关键字参数“decimal =','”转换数字字段。 Then, multiply the numerical fields by 1000. 然后,将数字字段乘以1000。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM