使用python numpy查找平均值

2024-05-17 13:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为'货币.csv'文件内容如下:

csv file

我需要用numpy计算5年内每种货币的平均汇率,每年每种货币的平均汇率,5年内每种货币的最低和最高汇率,五年期间每种货币汇率的标准差和每年每种货币汇率的标准差。你知道吗

有人能帮帮我吗?我是python领域的新手,在完成这项工作上遇到了困难。你知道吗


Tags: 文件csvnumpy内容汇率货币领域file
2条回答
'''
OP has a csv file with currency in it. He wants the average rate using each  currency
over the past 5 years, the average rate of each currency over each year, the
highest and lowest exchange rate of each currency over the past 5 years, and
the standard deviation of each currency over the past 5 years.
'''

import numpy as np

currencies = np.array([86.43, 87.45, 90.05, 90.20, 97.05, 20.95, 23.05, 29.76, 27.54, 25.55, 40.56, 47.69, 45.98, 45.89, 43.05]).reshape(3, 5)

mean_currency1 = np.mean(currencies[0,])
print('The mean exchange rate for currency 1 over the past 5 years is: {} '.format(mean_currency1))

mean_currency2 = np.mean(currencies[1,])
print('The mean exchange rate for currency 2 over the past 5 years is: {} '.format(mean_currency2))

mean_currency3 = np.mean(currencies[2,])
print('The mean exchange rate for currency 3 over the past 5 years is: {} '.format(mean_currency3))

year_1_currency1 = currencies[0, 0]
print('The average exhcnage rate value for currency 1 in year 1 was: {}'.format(year_1_currency1))

max_currency1 = np.max(currencies[0,])
print('The maximum exchange rate value for currency 1 over the past 5 years was: {}'.format(max_currency1))

min_currency1 = np.min(currencies[0,])
print('The minimum exchange rate value for currency 1 over the past 5 years was: {}'.format(min_currency1))

stdev_currency1 = np.std(currencies[0,])
print('The standard deviation for the exchange rate for currency 1 over the past 5 years was: {}'.format(stdev_currency1))

而不是创造你自己的np.数组,您只需使用.csv文件中的数据。我只是创建了自己的数组,因为我没有你的.csv汇率。我也没有找到每种货币的统计数据,因为我想让你大致了解你需要做什么。一旦你导入了.csv(如果你不知道如何导入数据,我也可以帮你),你只需要做一些切片就可以得到你想要的统计数据。因此,对于货币1,我们只需将第0行中的数据切片,就可以得到该行的平均值。我们可以为您所需要的每一行货币兑换率这样做。对于1年的平均值,我们可以取每年数据的平均值(如果没有这里显示的.csv文件格式,很难确切地知道您的数据是如何格式化的)。为了找到最小值和最大值,我们可以使用np最大值功能和np最小值用于每行货币汇率数据的函数(数据切片)。我们可以使用np.std标准函数来查找一行货币数据的标准差(假设您的货币汇率数据是按行格式化的)。最后,输出如下:

The mean exchange rate for currency 1 over the past 5 years is: 90.236 
The mean exchange rate for currency 2 over the past 5 years is: 25.37 
The mean exchange rate for currency 3 over the past 5 years is: 44.634 
The average exhcnage rate value for currency 1 in year 1 was: 86.43
The maximum exchange rate value for currency 1 over the past 5 years was: 97.05
The minimum exchange rate value for currency 1 over the past 5 years was: 86.43
The standard deviation for the exchange rate for currency 1 over the past 5 years was: 3.7071261106145252

如您所见,我没有对每种货币执行操作,但您只需要对要使用的行(或列,具体取决于csv的格式)进行切片。我做了你要求的一切,以货币1为例。你知道吗

相关问题 更多 >