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

标签 python numpy python-3.6

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

以下是我的尝试;

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

最佳答案

对于此类任务,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]

关于python - 使用 numpy/python 将具有相同索引的值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52465389/

相关文章:

python - 在 f-string 中格式化变量,小数位数可变

python - 正则表达式: Remove Time-Stamp from File-Name

python - 向量化 numpy 例程

python - 删除与另一个 CSV 中的行相同的行

python - 不同形状的 NumPy 数组集合的组合平均值和标准差

python - 了解 JSONEncoder 的子类化

python - 如何最大化非事件窗口?

python - 批量保存数据到图像: need speedup

python - 证书验证失败: certificate has expired (_ssl. c:1108)

python - 在 matplotlib 中使用 mpldatacursor 的工具提示