[英]Pandas Timegrouper on Dataframe using aggregate function count
我正在使用Excel中的數據框上的Timegrouper進行操作,嘗試使用Date作為列標題和Time作為行以及Y上的總計數的“ Pviot”是“ 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
使用重采樣,數據透視和時間分組器進行了嘗試,但出現了一系列錯誤
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
您可以按date
和time
拆分datetime
列,並使用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
缺少一項
使用帶有strftime
crosstab
將datetime
轉換為自定義字符串:
df.D = pd.to_datetime(df.D)
ndf = pd.crosstab(df['D'].dt.strftime('%H:%M').rename('H'), df['D'].dt.strftime('%Y-%m-%d'))
print (ndf)
D 2014-01-01 2014-01-02 2014-02-07
H
02:21 3 0 0
04:34 0 0 2
21:21 0 5 0
ndf = pd.crosstab(df['D'].dt.time.rename('T'), df['D'].dt.date)
print (ndf)
D 2014-01-01 2014-01-02 2014-02-07
T
02:21:51 3 0 0
04:34:50 0 0 2
21:21:01 0 5 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.