从pandas数据框列中的对象中删除逗号

2024-05-23 22:49:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我用熊猫导入了一个csv文件。

我的dataframe有多个列,标题是“Farm”、“Total Apples”和“Good Apples”。

为“总苹果”和“好苹果”导入的数字数据包含逗号,表示数千个,例如1200个等。 我想去掉逗号,使数据看起来像1200等

“Total Apples”和“Good Apples”列的变量类型作为对象出现。

我试过使用df.str.replacedf.strip,但没有成功。

还尝试将变量类型从object更改为string,将object更改为integer,但无法使其工作。

任何帮助都将不胜感激。

****编辑****

从使用pd.read_csv导入的csv文件中提取的数据:

Farm_Name   Total Apples    Good Apples
EM  18,327  14,176
EE  18,785  14,146
IW  635 486
L   33,929  24,586
NE  12,497  9,609
NW  30,756  23,765
SC  8,515   6,438
SE  22,896  17,914
SW  11,972  9,114
WM  27,251  20,931
Y   21,495  16,662

Tags: 文件csv数据苹果标题类型dataframedf
2条回答

我认为可以将参数thousands添加到^{},然后Total Apples列和Good Apples列中的值转换为integers

也许你的separator与众不同,别忘了改变它。如果分隔符是空白,则将其更改为sep='\s+'

import pandas as pd
import io

temp=u"""Farm_Name;Total Apples;Good Apples
EM;18,327;14,176
EE;18,785;14,146
IW;635;486
L;33,929;24,586
NE;12,497;9,609
NW;30,756;23,765
SC;8,515;6,438
SE;22,896;17,914
SW;11,972;9,114
WM;27,251;20,931
Y;21,495;16,662"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep=";",thousands=',')
print df
   Farm_Name  Total Apples  Good Apples
0         EM         18327        14176
1         EE         18785        14146
2         IW           635          486
3          L         33929        24586
4         NE         12497         9609
5         NW         30756        23765
6         SC          8515         6438
7         SE         22896        17914
8         SW         11972         9114
9         WM         27251        20931
10         Y         21495        16662
print df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 11 entries, 0 to 10
Data columns (total 3 columns):
Farm_Name       11 non-null object
Total Apples    11 non-null int64
Good Apples     11 non-null int64
dtypes: int64(2), object(1)
memory usage: 336.0+ bytes
None

试试这个:

locale.setlocale(locale.LC_NUMERIC, '')
df = df[['Farm Name']].join(df[['Total Apples', 'Good Apples']].applymap(locale.atof))

相关问题 更多 >