如何有效地处理欧洲的十进制分隔符使用pandas read_csv函数? [英] How to efficiently handle european decimal separators using the pandas read_csv function?

查看:403
本文介绍了如何有效地处理欧洲的十进制分隔符使用pandas read_csv函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 read_csv 将CSV文件读入pandas数据框。我的CSV文件包含大量的小数/浮点数。数字使用欧洲十进制符号进行编码:

  1.234.456,78 



这意味着'。'用作千位分隔符,','是十进制标记。



pandas 0.8。提供了一个名为千的read_csv参数来设置千位分隔符。是否还有一个额外的参数来提供小数点?如果没有,解析欧式样式十进制数的最有效的方法是什么?



目前我使用字符串替换,我认为是一个重大的性能惩罚。我使用的编码是:

 #转换为浮点数据类型,并将小数点从,改为。 '
f = lambda x:string.replace(x,u',',u'。')
df ['MyColumn'] = df ['MyColumn'] map(f)

感谢任何帮助。



$ b Thomas

解决方案

您可以使用转换器 c $ c> read_csv 。给定 /tmp/data.csv 如下:

 x ,y
one,1.234,56
two,2.000,00

你可以:

 在[20]:pandas.read_csv('/ tmp / data.csv',converters = {'y':lambda x:float(x.replace('。','')。replace(',','。')))
Out [20] :
xy
0 one 1234.56
1 two 2000.00


I'm using read_csv to read CSV files into pandas data frames. My CSV files contain large numbers of decimals/floats. The numbers are encoded using the european decimal notation:

1.234.456,78

This means that the '.' is used as the thousand seperator and the ',' is the decimal mark.

pandas 0.8. provides a read_csv argument called 'thousands' to set the thousand seperator. Is there an additional argument to provide the decimal mark as well? If no, what is the most effcient way to parse a europen style decimal number?

Currently i'm using string replace which i consider to be a significant perfomance penalty. The coding i'm using is this:

# Convert to float data type and change decimal point from ',' to '.'
f = lambda x: string.replace(x, u',', u'.')
df['MyColumn'] = df['MyColumn'].map(f)

Any help is appreciated.

Thanks, Thomas

解决方案

You can use the converters kw in read_csv. Given /tmp/data.csv like this:

"x","y"                                                                         
"one","1.234,56"                                                                
"two","2.000,00"   

you can do:

In [20]: pandas.read_csv('/tmp/data.csv', converters={'y': lambda x: float(x.replace('.','').replace(',','.'))})
Out[20]: 
     x        y
0  one  1234.56
1  two  2000.00

这篇关于如何有效地处理欧洲的十进制分隔符使用pandas read_csv函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆