python - 如何在时间序列中使用 mean() 并将其放到列中?
问题描述
我有这个问题:
bitcoin = pd.read_csv('./Bitcoin/BTC-USD.csv')
bitcoin
然后我每天都有比特币的价值......但实际上我想要 2018 年和 2019 年每个月的平均值:
bitcoin['Date']=pd.to_datetime(bitcoin['Date'],format="%Y-%m-%d")
bitcoin = bitcoin[(bitcoin['Date']>'2018-01-01') & (bitcoin['Date']<'2020-01-01')]
bitcoin_mean =bitcoin['High'].groupby([bitcoin['Date'].dt.year,bitcoin['Date'].dt.month]).mean()
bitcoin_mean
这很好,但实际上我想要它在 3 个不同的列中,因为我想绘制它,比如 'Year' , 'Day' 和 'Averaged_price' 整数,我该怎么做?
提前致谢!
解决方案
import pandas as pd
Lownload BTC-USD.csv
from here, I also put it on Github Gists.
Read in dataframe:
df = pd.read_csv('BTC-USD.csv')
Then you can get the average for every month:
df.groupby(df['Date'].apply(lambda row: row.split('-')[1])).mean()
which will give you:
(The first column is the months, 01 is January, 02 February, etc...)
Why this works
df['Date'].apply(lambda row: row.split('-')[1])
is a series:
0 08
1 08
2 08
3 08
4 08
..
362 08
363 08
364 08
365 08
366 08
Name: Date, Length: 367, dtype: object
It takes the date from each row, ie 2019-08-24
, split()
s it by -
, so it gets a list: ['2019','08','24]. It takes the 1-indexed (ie second) element from that list, ie month. We groupby() this variable & then take the mean() to compute mean of groups (search for mean()
here).
推荐阅读
- java - 错误:变量总计可能尚未初始化
- c++ - 为 beaglebone black 交叉编译时无法链接 opencv-3.2.0
- c++ - 如何在c ++中的mysql_fetch_row(MYSQL _RES)中存储值行[i]
- c - 为什么在下面的代码中两个不同的变量具有相同的地址但不同的值?
- javacc - 如何根据 JavaCC 中的用户输入多次调用一个方法?
- javascript - 如何改进正则表达式,使其可以匹配谷歌脚本电子邮件刮板的电子邮件格式?
- webstorm - WebStorm 新版本断点不起作用
- python - 如何解决单源多目的地问题的不连续性?
- c# - 作为 Windows 服务运行的多线程控制台应用程序(使用 Topshelf)
- c# - 二进制搜索无法搜索包含空格的数据,如何解决?