[英]creating new column with the sum of the past 24 hours
For the following dataframe: df_data, is there a way to make a new column that counts the nr of vehicles of the past 24 hours or just of the previous day?对于以下 dataframe:df_data,有没有办法创建一个新列来计算过去 24 小时或前一天的车辆数量?
df_data = {'day_of_year' : [1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2], 'nr_of_vehicles' : [254,154,896,268,254,501,840,868,654,684,684,681,632,468,987,134,336,119,874,658,121,254,154,896,268,254,501,840,868,654,684,684,681,632,468,987,134,336,119,874,658,121,268,254,501,840,868,654], 'hour' : [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]}
Visual representation (nr_of_vehicles is counted per hour):视觉表示(nr_of_vehicles 每小时计数):
I thought of grouping the data by day_of_year by using the following我想通过使用以下方法按 day_of_year 对数据进行分组
df_data_day = df_data.groupby('day_of_year').agg({'nr_of_vehicles': 'sum'})
but I don't know how I could assign it correctly to the column, because the are more rows in the original dataframe.但我不知道如何将其正确分配给列,因为原始 dataframe 中有更多行。
You were not far: you had just to use transform
instead of agg
:你不远:你只需要使用
transform
而不是agg
:
df_data_day = df_data.groupby('day_of_year')['nr_of_vehicles'].transform('mean')
You can even directly add a new column:您甚至可以直接添加一个新列:
df_data['nr_by_day'] = df_data.groupby('day_of_year')['nr_of_vehicles'].transform('mean')
BTW: I used your proposed code which computes the average, when your title says sum...顺便说一句:当你的标题说总和时,我使用了你提出的计算平均值的代码......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.