![](/img/trans.png)
[英]How do the sum of a column with group by date from datetime ? Python Pandas
[英]Python Pandas Group by date using datetime data
我有一個Date_Time
列,我希望在不創建新列的情況下按日期時間Date_Time
。 這可能是我當前的代碼不起作用。
df = pd.groupby(df,by=[df['Date_Time'].date()])
您可以使用groupby
by 列Date_Time
by dt.date
日期:
df = df.groupby([df['Date_Time'].dt.date]).mean()
樣本:
df = pd.DataFrame({'Date_Time': pd.date_range('10/1/2001 10:00:00', periods=3, freq='10H'),
'B':[4,5,6]})
print (df)
B Date_Time
0 4 2001-10-01 10:00:00
1 5 2001-10-01 20:00:00
2 6 2001-10-02 06:00:00
print (df['Date_Time'].dt.date)
0 2001-10-01
1 2001-10-01
2 2001-10-02
Name: Date_Time, dtype: object
df = df.groupby([df['Date_Time'].dt.date])['B'].mean()
print(df)
Date_Time
2001-10-01 4.5
2001-10-02 6.0
Name: B, dtype: float64
使用resample
另一種解決方案:
df = df.set_index('Date_Time').resample('D')['B'].mean()
print(df)
Date_Time
2001-10-01 4.5
2001-10-02 6.0
Freq: D, Name: B, dtype: float64
resample
df.resample('D', on='Date_Time').mean()
B
Date_Time
2001-10-01 4.5
2001-10-02 6.0
Grouper
正如@JosephCottam 所建議的
df.set_index('Date_Time').groupby(pd.Grouper(freq='D')).mean()
B
Date_Time
2001-10-01 4.5
2001-10-02 6.0
TimeGrouper
您可以將索引設置為'Date_Time'
並使用pd.TimeGrouper
df.set_index('Date_Time').groupby(pd.TimeGrouper('D')).mean().dropna()
B
Date_Time
2001-10-01 4.5
2001-10-02 6.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.