我正在尝试跟踪并完成 this video tutorial韦斯·麦金尼 (Wes McKinney) 着。我已经到了我们正在研究婴儿名字示例的地步,而且我在编写的代码和 his code 中都遇到了同样的问题。 (BabyNames.ipynb)。
作为引用,我在 Mac (OS X 10.10.1) 上使用:
- python 2.7.6
- IPython 2.3.1
- Pandas 0.15.2
我可以成功地做到这一切:
names = read_csv('baby-names2.csv') # read the data in
boys = names[names.sex == 'boy'] # create boys list
girls = names[names.sex == 'girl'] # create girls list
# create a function
def get_quantile_count(group, quantile=0.5):
df = group.sort_index(by='prop', ascending=False)
return df.prop.cumsum().searchsorted(quantile)
# call the function
boys.groupby('year').apply(get_quantile_count)
这给我的输出看起来像这样(为简洁起见,只显示一小部分数据):
year
1880 [15]
1881 [15]
1882 [17]
1883 [17]
1884 [19]
1885 [20]
1886 [20]
1887 [21]
1888 [22]
1889 [22]
1890 [23]
1891 [24]
1892 [25]
然后我想绘制这些数据,如下所示:
boys.groupby('year').apply(get_quantile_count).plot()
但它给了我这个错误:
TypeError: Empty 'Series': no numeric data to plot
在观看视频时,他显示的数据在数据框中的数字周围没有方括号 [ ]。我猜这就是导致我出现问题的原因。
有人知道如何改变这个吗?我正在观看视频并自己编写代码,但如果我运行提供的笔记本 BabyNames.ipynb,也会发生同样的事情。
请您参考如下方法:
看来我过早发布了这个问题。我离开了一会儿,然后意识到这是一个简单的解决方法。
问题是函数 searchsorted() 返回给我一个数组,而我只需要数组中的单个项目。很容易。修改函数为:
# create a function
def get_quantile_count(group, quantile=0.5):
df = group.sort_index(by='prop', ascending=False)
return df.prop.cumsum().searchsorted(quantile)[0]
只是使用索引 0 从数组中取出数字。不知道为什么我在这方面遇到了这么困难。我想那个函数一定是在最近改变了它的返回类型?还是我有一些设置不正确的选项?不知道,但至少这解决了问题。
