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

标签 python pandas

我正在尝试读取一些人口数据作为学习 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/

相关文章:

python - 参数化泛型不能与类或实例检查一起使用

python - 比较两个无序列表中各个元素的差异

python - 接收: "UnboundLocalError: local variable referenced before assignment"

python - 使用 yamltodb 将 YAML 数据转换为数据框

python - 在 Pandas 中使用 astype 不会给出预期的结果

python - Pandas 在数据框列上滑动窗口

python - 使用时间序列时在 Pandas 滚动中使用中心

ubuntu - Python3 和 Pandas

python - 根据值从一组列中选择一个值并使用该值创建新列?

python - pygame.time.set_timer() 事件重置?