gpt4 book ai didi

python - Pandas read_table() 数千 =',' 不工作

转载 作者:行者123 更新时间:2023-11-30 23:31:16 26 4
gpt4 key购买 nike

我正在尝试读取一些人口数据作为学习 pandas 的练习:

>>> countries = pd.read_table('country_data.txt',
thousands=',',
header=None,
names=["Country Name", "Area (km^2)", "Areami2",
"Population", "Densitykm2", "Densitymi2",
"Date", "Source"],
usecols=["Country Name", "Area (km^2)", "Population"],
index_col="Country Name"
)
>>> countries.head()

给出

                Area (km^2) Population
Country Name
Monaco 2 36,136
Singapore 716 5,399,200
Vatican City 0.44 800
Bahrain 757 1,234,571
Malta 315 416,055

尽管我指定了数千=',',但看起来人口正在被读取为字符串:

>>> countries.ix["Singapore"]["Population"]
'5,399,200'

我尝试在对 read_table 的调用中移动“thousands=','”位,并检查数据以查看是否有问题,但那里只有数字值,而我没有知道还能去哪里看...

最佳答案

这是a bug in 0.12 ,并已在(即将发布)0.13 中修复。

在那之前,我建议手动修改列:

In [11]: df['Population'].str.replace(',', '').astype(int)  # or float
Out[11]:
0 36136
1 5399200
2 800
3 1234571
4 416055
Name: Population, dtype: int64

In [12]: df['Population'] = df['Population'].str.replace(',', '').astype(int)

关于python - Pandas read_table() 数千 =',' 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20037691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com