在对象中添加数字

时间:2014-02-13 08:05:00

标签: python arrays object matplotlib

我正在尝试添加与特定年份配对的数字,然后在同一图表上绘制结果。

数组以这种方式格式化:

[(year, [one or two nums]),(year, [one or two nums]),(year, [one or two nums]),... ]

以下是可在以下网址找到数据的代码:https://raw2.github.com/hadley/data-baby-names/master/baby-names.csv

import pandas
import pylab
import matplotlib
from pandas import *
from pylab import *
from matplotlib import *

names = read_csv(r'C:\Users\joe\Documents\Python\baby-names2.csv')
print (names.head())

import matplotlib as mpl
import matplotlib.pyplot as plt



resultAry = names[names.name.isin(['Joseph', 'Nancy'])].set_index(['year','name','sex'])['prop']
resultAry = resultAry.groupby(level='name')
print (resultAry.head())
print ('***************')
resultAry = resultAry.groupby(level='year')
print (resultAry)
#resultAry = resultAry.plot()

name
Joseph    [(1880, [0.022209, 0.000102]), (1881, [0.02267...
Nancy     [(1880, [0.004211]), (1881, [0.004339]), (1882...
dtype: object

理想情况下,数组会列出年份以及随其列出的两个比例的总和。

准码

[(year1,[prop1 + prop2(if exists)]),(year2,[prop1 + prop2(if exists)])...]

在第一个嵌入列表中输出会有所不同     名称     约瑟夫[(1880,[0.022331]),(1881,[0.02267 ...     南希[(1880,[0.004211]),(1881,[0.004339]),(1882 ......     dtype:object

此问题是来自其他帖子的结转:plotting in python with congruent x-values

2 个答案:

答案 0 :(得分:1)

end_list = []
for year, nums in items:
    for num in nums:
        end_list.append((year, [num]))

不是最优雅的解决方案,但它可以完成工作。

答案 1 :(得分:1)

你想所有与一年相关的数字吗?

arr = [ (1880, [ 0.25, 0.5 ]), (1881, [ 0.125, 0.25 ]), (1882, [ 0.5, 0.75 ]) ]

for i, (year, numbers) in enumerate(arr):
    arr[i][1][:] = [ sum(numbers) ]
print arr

这将打印:

[(1880, [0.75]), (1881, [0.375]), (1882, [1.25])]