![](/img/trans.png)
[英]python pandas: applying different aggregate functions to different columns
[英]Applying different aggregate functions to different columns (now that dict with renaming is deprecated)
之前我曾問過這個問題: python pandas:將不同的聚合函數應用到不同的列,但對pandas https://github.com/pandas-dev/pandas/pull/15931的最新更改意味着我認為是優雅和pythonic解決方案已被棄用,原因我真的無法理解。
問題是,現在仍然是:當進行groupby時,如何將不同的聚合函數應用於不同的字段(例如x的總和,x的平均值,y的最小值,z的最大值等)並重命名結果字段,一氣呵成,或者至少以一種可能的pythonic而不是太麻煩的方式? 即sum_x不會,我需要顯式重命名字段。
這種方法,我喜歡:
df.groupby('qtr').agg({"realgdp": {"mean_gdp": "mean", "std_gdp": "std"},
"unemp": {"mean_unemp": "mean"}})
將被棄用,現在產生此警告:
FutureWarning: using a dict with renaming is deprecated and will be removed in a future version
謝謝!
不推薦使用agg(),而是使用agg重命名。
請查看文檔: https : //pandas.pydata.org/pandas-docs/stable/whatsnew.html#deprecate-groupby-agg-with-a-dictionary-when-renaming
不推薦使用的內容:1。將dict傳遞給分組/滾動/重采樣系列,允許重命名生成的聚合2.將dict-of-dicts傳遞給分組/滾動/重采樣的DataFrame。
這將有效,但它不是一行代碼
df.groupby('qtr').agg({"realgdp": ["mean", "std"], "unemp": "mean"})
df.columns = df.columns.map('_'.join)
df.rename(columns = {'realgdp_mean': 'mean_gdp', 'realgdp_std':'std_gdp', 'unemp_mean':'mean_unemp'}, inplace = True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.