pandas 如何将数据帧的单个值除以月平均值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15297053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I divide single values of a dataframe by monthly averages?
提问by Markus W
I have the following 15 minute data as a dataframefor 3 years. With the first two columns being the index.
我有以下 15 分钟的数据作为dataframe3 年。前两列是索引。
2014-01-01 00:15:00 1269.6
2014-01-01 00:30:00 1161.6
2014-01-01 00:45:00 1466.4
2014-01-01 01:00:00 1365.6
2014-01-01 01:15:00 1362.6
2014-01-01 01:30:00 1064.0
2014-01-01 01:45:00 1171.2
2014-01-01 02:00:00 1171.0
2014-01-01 02:15:00 1330.4
2014-01-01 02:30:00 1309.6
2014-01-01 02:45:00 1308.4
2014-01-01 03:00:00 1494.0
I have used resampleto get a second series with monthly averages.
我曾经resample获得过每月平均值的第二个系列。
data_Monthly = data.resample('1M', how='mean')
How can I divide the values in the last column by their monthly average with the result being still a time series on 15 minute granularity?
如何将最后一列中的值除以其月平均值,结果仍然是 15 分钟粒度的时间序列?
回答by Zelazny7
First make a grouper:
首先制作一个石斑鱼:
import pandas as pd
In [1]: grouper = pd.TimeGrouper("1M")
Then make your new column:
然后创建你的新列:
In [2]: df['normed'] = df.groupby(grouper).transform(lambda x: x/x.mean())
By passing grouper to the groupbymethod you group your data into one month chunks. Within each chunk you divide the 15 minute interval datum by the mean for that month.
通过将 grouper 传递给该groupby方法,您可以将数据分组为一个月的块。在每个块中,您将 15 分钟间隔数据除以该月的平均值。
回答by Manik bhandari
I think it is generally recommended to use Grouper instead of TimeGrouper. Have a look at this. For example, if your column is called Date, use
我认为一般建议使用Grouper而不是TimeGrouper。看看这个。例如,如果您的列名为 Date,请使用
grouper = pd.Grouper(key='Date', freq='M')
instead of using TimeGrouper and then continue as @Zelazny7 suggested. If your column is not a datetime index then use
而不是使用 TimeGrouper,然后按照@Zelazny7 的建议继续。如果您的列不是日期时间索引,则使用
df['Date'] = pd.to_datetime(df['Date'])
回答by Warren O'Neill
This can be done in one line with:
这可以在一行中完成:
df.groupby([df.index.year, df.index.month]).transform(lambda x: x/x.mean())
回答by poonam poonia
data_Monthly = data.resample('M',on='Date').mean()
data_Monthly = data.resample('M',on='Date').mean()

