Python 数据帧内的分组、求和、排序和选择
我有这样一个数据帧:Python 数据帧内的分组、求和、排序和选择,python,pandas,Python,Pandas,我有这样一个数据帧: df=pd.DataFrame({'State' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], 'County' : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 'Population': [10, 11, 12, 13, 17, 16, 15, 18, 14]}) 看看每个州人口最多的两个县,人口最多的两个州是什么(按人口
df=pd.DataFrame({'State' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
'County' : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
'Population': [10, 11, 12, 13, 17, 16, 15, 18, 14]})
看看每个州人口最多的两个县,人口最多的两个州是什么(按人口最高到人口最低的顺序排列)
我通过使用循环解决了这个问题,现在我正在尝试得到相同的结果——分组、求和、排序和选择。
下面的代码是有效的,但我相信有很多不同的、更优雅的方法可以做到这一点
df.groupby(['State'])['Population'].nlargest(2).groupby(['State']).sum()\
.sort_values(ascending=False)[:2].to_frame()\
.reset_index()['State'].tolist()
你不能把这个缩短一点
df.groupby(['State'])['Population'].nlargest(2)\
.sum(level=0).sort_values(ascending=False).index[:2].tolist()
无需转换回dataframe来检索状态,只需直接从索引中获取状态即可。将
sum
与level
参数一起使用只不过是一种简短的语法,它再次超越了groupby。您不能缩短这一点
df.groupby(['State'])['Population'].nlargest(2)\
.sum(level=0).sort_values(ascending=False).index[:2].tolist()
(df.sort_values('Population', ascending=False) # order by highest population per country
.groupby('State').head(2) # get two most populous counties per state
.groupby('State').sum() # get population of two largest counties per state
.sort_values('Population', ascending = False)[:2] # get top 2 states by population
.index # get states names
.tolist() # convert to list
)
无需转换回dataframe来检索状态,只需直接从索引中获取状态即可。将sum
与level
参数一起使用只是一种简短的语法,再次超越了groupby
(df.sort_values('Population', ascending=False) # order by highest population per country
.groupby('State').head(2) # get two most populous counties per state
.groupby('State').sum() # get population of two largest counties per state
.sort_values('Population', ascending = False)[:2] # get top 2 states by population
.index # get states names
.tolist() # convert to list
)
这里有另一种方法来解释每个操作
这里有另一种方法来解释每个操作欢迎来到Stack Overflow并感谢您提供的答案。你能把每个方法分成几行吗?这将使Pandas/Python的新用户更容易阅读。欢迎来到Stack Overflow,感谢您提供的答案。你能把每个方法分成几行吗?这将使Pandas/Python的新用户更容易阅读。