【发布时间】:2017-05-29 16:09:45
【问题描述】:
我有一个类似于以下的数据框:
import pandas as pd
entry_1 = pd.Series({'State': 'State1', 'County': 'name1', 'Population': 10})
entry_2 = pd.Series({'State': 'State1', 'County': 'name12', 'Population': 8})
entry_3 = pd.Series({'State': 'State1', 'County': 'name13', 'Population': 7})
entry_4 = pd.Series({'State': 'State1', 'County': 'name14', 'Population': 6})
entry_5 = pd.Series({'State': 'State2', 'County': 'name15', 'Population': 10})
entry_6 = pd.Series({'State': 'State2', 'County': 'name16', 'Population': 8})
entry_7 = pd.Series({'State': 'State2', 'County': 'name17', 'Population': 7})
entry_8 = pd.Series({'State': 'State2', 'County': 'name18', 'Population': 6})
entry_9 = pd.Series({'State': 'State3', 'County': 'name19', 'Population': 10})
entry_10 = pd.Series({'State': 'State3', 'County': 'name10', 'Population':8})
entry_11 = pd.Series({'State': 'State3', 'County': 'name11', 'Population':7})
entry_12 = pd.Series({'State': 'State3', 'County': 'name12', 'Population':6})
entry_13 = pd.Series({'State': 'State4', 'County': 'name13', 'Population':1})
entry_14 = pd.Series({'State': 'State4', 'County': 'name14', 'Population':2})
entry_15 = pd.Series({'State': 'State4', 'County': 'name15', 'Population':3})
df = pd.DataFrame([
entry_1, entry_2,entry_3,entry_4,entry_5,entry_6,entry_7,
entry_8,entry_9,entry_10,entry_11,entry_12, entry_13, entry_14, entry_15])
df.head()
使用一个州内人口最多的三个县,我需要找到 人口最多的三个州,按人口最多的顺序排列 最低。
我做了一个我认为有意义的尝试,尽管我没有得到预期的结果。我无法用示例代码复制它,但我想可能有缺失值,或者类似的东西导致计算失败..
df['SUM_OF_TOP'] = df.groupby('State')['Population'].nlargest(3).sum(level=1)
largest_States = df['SUM_OF_TOP'].nlargest(3).index
[df.loc[idx]['State'] for idx in largest_States]
>>> ['State1', 'State2', 'State3']
对于可能出现的问题有什么建议吗?我才刚开始接触 Pandas,所以我很无知..
【问题讨论】:
标签: pandas