1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
1)要確定一列是否為數(shù)字,您可以使用pandas.api.types.is_numeric_dtype
2)要查找剩余的列,您可以使用set(df.columns)減去您使用的列g(shù)roupby以及具有特定聚合函數(shù)的列,例如
from pandas.api.types import is_numeric_dtype
fields_groupby = ['Day', 'Month']
fields_specific = {
'High': [min, 'mean', max],
'Low': [min, 'mean', max],
'Open': 'mean',
'Size': lambda x: x.value_counts().index[0],
}
fields_other = set(set(stock.columns) - set(fields_groupby) - set(fields_specific))
fields_agg_remaining = {col: 'mean' if is_numeric_dtype(stock[col]) else lambda x: x.value_counts().index[1] for col in fields_other}
之后,將 和 的集合組合為fields_specificaggfields_agg_remaining字段列表
agg_fields = fields_agg_remaining
agg_fields.update(fields_specific)
stock.groupby(['Day', 'Month']).agg(agg_fields).round(2)
編輯:您可以組合所有內(nèi)容以將它們放入字典參數(shù)中,例如:
stock.groupby(['Day', 'Month']).agg(
{col:
[min, 'mean', max] if col in ['High', 'Low'] else
'mean' if col in ['Open'] else
lambda x: x.value_counts().index[0] if col in ['Size'] else
'mean' if is_numeric_dtype(stock[col]) else
lambda x: x.value_counts().index[1] for col in set(set(stock.columns) - {'Day', 'Month'})}
).round(2)
添加回答
舉報(bào)