我有一个带有['DateTime', 'Variable']
栏的熊猫数据,我正试图在last 中为每个Variable
获得滚动计数。思维中枢可以用在某种程度上。
样本数据
DateTime Variable
8/24/19 3:30PM A
8/24/19 3:32PM A
8/24/19 3:36PM B
8/24/19 3:50PM C
8/25/19 2:50PM A
预期产出
DateTime A B C
8/24/19 3:30PM 1 0 0
8/24/19 3:32PM 2 0 0
8/24/19 3:36PM 2 1 0
8/24/19 3:50PM 2 1 1
8/25/19 2:50PM 1 0 0
新变量可能会被添加或删除,所以我希望有一个动态的解决方案。
发布于 2020-10-03 19:47:36
实际上,您可以从pivot
开始,或者用groupby.unstack
手工完成它。
然后,您正在寻找df.rolling
来创建可以与许多函数聚合的滚动窗。为了使用时间增量(在本例中为1小时)创建窗口,您需要确保索引是datetime
类型的。
df['DateTime'] = pd.to_datetime(df['DateTime'])
out = (
df
.groupby(['DateTime', 'Variable']) # set the columns as index
.size() # aggregate by row count
.unstack(fill_value=0) # move 'Variable' index level to columns
.sort_index()
)
out = out.rolling('1h').sum()
输出
Variable A B C
DateTime
2019-08-24 15:30:00 1.0 0.0 0.0
2019-08-24 15:32:00 2.0 0.0 0.0
2019-08-24 15:36:00 2.0 1.0 0.0
2019-08-24 15:50:00 2.0 1.0 1.0
2019-08-25 14:50:00 1.0 0.0 0.0
发布于 2020-10-03 19:01:35
考虑到df是您的数据集: new_df =df[df‘’Variable‘=’A‘’].resample(‘H’).count()
您可以创建一个新的数据,如下所示: final_df =pd.DataFrame({‘DateTime’:newdf.index,'A':new_df.values})
类似地,获取变量列的每个类别的计数,并尝试使用循环将其连接到final_df。
我还没试过,但希望能成功。
https://stackoverflow.com/questions/64187679
复制相似问题