簡體   English   中英

在 pandas 中保留列,而 groupby(periodindex) df

[英]Keep columns while groupby(periodindex) df in pandas

我想保留 df 的其他列

df=df.groupby(pd.PeriodIndex(df['date'], freq='M'))['Close/Last'].mean().reset_index()

如何在 df 中保留其他列?

我認為.agg()非常適合這里:

請記住import numpy as np

代替:

df=df.groupby(pd.PeriodIndex(df['date'], freq='M'))['Close/Last'].mean().reset_index()

嘗試這個:

df=df.groupby(pd.PeriodIndex(df['date'], freq='M')).agg({'Close/Last': (np.mean),'Volume':'first','Name':'first'})

.agg()允許您選擇對列執行的操作(應用函數),但如果您只想保留它們,請使用 .agg({'col1': 'first', 'col2': 'first', . ..} ETC。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM