python - 尝试使用 Pandas 和 Python 绘图时出现空系列

标签 python python-2.7 pandas

我正在尝试遵循并解决 this video tutorial作者:韦斯·麦金尼。我已经到了我们正在查看婴儿名字示例的地步,我在编写的代码和 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 从数组中获取数字。不知道为什么我对此感到如此困难。我猜这个函数最近一定改变了它的返回类型?或者我的某些选项设置不正确?不知道,但至少可以解决这个问题。

关于python - 尝试使用 Pandas 和 Python 绘图时出现空系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27747410/

相关文章:

python - 套接字编程;通过多个设备传输时文件损坏

python - 无法将稀疏矩阵写入 csv

multithreading - 线程 : PyQt crashes with "unknown request in queue while dequeuing"

python - 按分数比较数据帧列中的值

python - 如何将多个文件夹中相似命名的文件合并到每个文件名的一个文件夹中

python - 匹配列表python中相反数字的出现

python - Python 中的 NZEC 错误

python - 重命名 Pandas 中的选定列

python - 在 python 中的两个对象之间存储和使用信息的最佳方式是什么?

python - 为什么 len(a[0]) 与 a.shape[1] 不同