[英]Pandas: how to calculate a rolling window over one column (grouped by date) and count distinct values of another column?
[英]How to calculate mean values grouped on another column in Pandas
對於以下數據框:
StationID HoursAhead BiasTemp
SS0279 0 10
SS0279 1 20
KEOPS 0 0
KEOPS 1 5
BB 0 5
BB 1 5
我想得到類似的東西:
StationID BiasTemp
SS0279 15
KEOPS 2.5
BB 5
我知道我可以編寫這樣的腳本以獲得所需的結果:
def transform_DF(old_df,col):
list_stations = list(set(old_df['StationID'].values.tolist()))
header = list(old_df.columns.values)
header.remove(col)
header_new = header
new_df = pandas.DataFrame(columns = header_new)
for i,station in enumerate(list_stations):
general_results = old_df[(old_df['StationID'] == station)].describe()
new_row = []
for column in header_new:
if column in ['StationID']:
new_row.append(station)
continue
new_row.append(general_results[column]['mean'])
new_df.loc[i] = new_row
return new_df
但我想知道大熊貓是否有更直接的東西。
你可以groupby
上StationID
然后取mean()
上BiasTemp
。 要輸出Dataframe
,請使用as_index=False
In [4]: df.groupby('StationID', as_index=False)['BiasTemp'].mean()
Out[4]:
StationID BiasTemp
0 BB 5.0
1 KEOPS 2.5
2 SS0279 15.0
如果沒有as_index=False
,它會返回一個Series
In [5]: df.groupby('StationID')['BiasTemp'].mean()
Out[5]:
StationID
BB 5.0
KEOPS 2.5
SS0279 15.0
Name: BiasTemp, dtype: float64
在這個 pydata教程中閱讀更多關於groupby
。
可以按如下方式完成:
df.groupby('StationID').mean()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.