我有一個如下所示的數據框。df = pd.DataFrame({ 'Country':['A','A','A','A','A','A','B','B','B'], 'City':['C 1','C 1','C 1','B 2','B 2','B 2','C 1','C 1','C 1'], 'Date':['7/1/2020','7/2/2020','7/3/2020','7/1/2020','7/2/2020','7/3/2020','7/1/2020','7/2/2020','7/3/2020'], 'Value':[46,90,23,84,89,98,31,84,41]})我需要創建 2 個平均值首先,以Country和City為標準其次,僅對Country為了實現這一點,我們可以輕松編寫以下代碼df.groupby(['Country','City']).agg('mean')+---------+------+-------+| Country | City | Value |+---------+------+-------+| A | B 2 | 90.33 || +------+-------+| | C 1 | 53 |+---------+------+-------+| B | C 1 | 52 |+---------+------+-------+df.groupby(['Country']).agg('mean'). +---------+-------+ | Country | | +---------+-------+ | A | 71.67 | +---------+-------+ | B | 52 | +---------+-------+上述 2 個代碼中唯一的變化是groupbycriteria City。除此之外一切都一樣。所以有明顯的重復/重復的代碼。(特別是當涉及到復雜的場景時)?,F在我的問題是,有什么方法可以讓我們編寫一個代碼來同時合并這兩種場景。DRY——不要重復自己。我的想法如下。Choice = 'City' `<<--Here I type either City or None or something based on the requirement. Eg: If None, the Below code will ignore that criteria.`df.groupby(['Country',Choice]).agg('mean')這可能嗎?或者有效地編寫上述代碼而不重復的最佳方法是什么?
1 回答

冉冉說
TA貢獻1877條經驗 獲得超1個贊
我不確定你想要完成什么但是..為什么不只使用 if 呢?
columns=['Country']
if Choice:
columns.append(Choice)
df.groupby(columns).agg('mean')
添加回答
舉報
0/150
提交
取消