我正在 Excel 的数据框上使用 Timegrouper,并尝试使用日期作为列标题并使用时间作为行来执行 Pviot,Y 上的聚合计数是“Barton LLC”。
Data.xls
X Y Z D
740150 Barton LLC B1-20000 2014-01-01 02:21:51
740150 Barton LLC B1-50809 2014-01-01 02:21:51
740150 Barton LLC B1-53102 2014-01-01 02:21:51
740150 Barton LLC S2-16558 2014-01-02 21:21:01
740150 Barton LLC B1-86481 2014-01-02 21:21:01
740150 Curlis L S1-06532 2014-01-02 21:21:01
740150 Barton LLC S1-47412 2014-01-02 21:21:01
740150 Barton LLC B1-33364 2014-01-02 21:21:01
740150 Barton LLC S1-93683 2014-02-07 04:34:50
740150 Barton LLC S2-10342 2014-02-07 04:34:50
尝试使用 resample 和 pivot 以及 timegrouper 但得到了一系列错误
import pandas as pd
import numpy as np
df = pd.read_excel("data.xlsx")
ndf = df[df['Type'].eq('df')].pivot_table(columns= ['Y'],values='Y',
index=pd.Grouper(key='D',freq='H'),aggfunc='count',fill_value=0)
结果
2014-01-01,2014-01-02,2014-02-07
02:21 3,NaN,NaN
21:21 NaN,4,NaN
04:34 NaN,NaN,2
最佳答案
您可以将 datetime
列拆分为 date
和 time
并使用 pivot_table
:
df['date'] = df['D'].dt.date
df['time'] = df['D'].dt.time
pd.pivot_table(df, 'D', 'time', 'date', aggfunc='count')
date 2014-01-01 2014-01-02 2014-02-07
time
02:21:51 3.0 NaN NaN
04:34:50 NaN NaN 2.0
21:21:01 NaN 5.0 NaN
请注意,您遗漏了日期 2014-01-02 21:21:01
关于python - 使用聚合函数计数的 Dataframe 上的 Pandas Timegrouper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54021773/