使用numpy / python将具有相同索引的值相加

时间:2018-09-23 10:53:13

标签: python numpy python-3.6

我是python和numpy的新手。我想找到总降雨天数(即,每年E列的总和,并附上图片)。 我正在使用 numpy.unique 查找数组year的唯一元素。

以下是我的尝试;

import numpy as np
data = np.genfromtxt("location/ofthe/file", delimiter = " ")
unique_year = np.unique(data[:,0], return_index=True)
print(unique_year)
j= input('select one of the unique year: >>>  ')
#Then I want to give the sum of the rainfall days in that year.

如果有人可以帮助我,我将不胜感激。 预先感谢。

enter image description here

1 个答案:

答案 0 :(得分:1)

对于此类任务,Pandas(基于NumPy构建)更容易适应。

在这里,您可以使用GroupBy创建系列映射。然后,您可以使用输入来查询您的系列:

import pandas as pd

# read file into dataframe
df = pd.read_excel('file.xlsx')

# create series mapping from GroupBy object
rain_days_by_year = df.groupby('year')['Rain days(in numbers)'].sum()

# get input as integer
j = int(input('select one of the unique year: >>>  '))

# extract data
res = rain_days_by_year[j]