如何在Pandas的数据框子集中获得最大值?
例如,当我做
之类的事情时statedata[statedata['state.region'] == 'Northeast'].ix[statedata['Murder'].idxmax()]
我得到一个KeyError,表明idxmax
正在返回全局最大值Alabama的密钥,而不是查询子集中的最大值(当然缺少该密钥)。
有没有办法在熊猫上简明扼要地做到这一点?
作为参考,此处使用的数据来自R,使用
data(state)
statedata = cbind(data.frame(state.x77), state.abb, state.area, state.center, state.division, state.name, state.region)
然后从R导出并由Pandas导入。
答案 0 :(得分:3)
您可以使用df.loc选择子数据框:
import pandas as pd
import pandas.rpy.common as com
import rpy2.robjects as ro
r = ro.r
statedata = r('''cbind(data.frame(state.x77), state.abb, state.area, state.center,
state.division, state.name, state.region)''')
df = com.convert_robj(statedata)
df.columns = df.columns.to_series().str.replace('state.', '')
subdf = df.loc[df['region']=='Northeast', 'Murder']
print(subdf)
# Connecticut 3.1
# Maine 2.7
# Massachusetts 3.3
# New Hampshire 3.3
# New Jersey 5.2
# New York 10.9
# Pennsylvania 6.1
# Rhode Island 2.4
# Vermont 5.5
# Name: Murder, dtype: float64
print(subdf.idxmax())
打印
New York
选择每个地区谋杀率最高的州(as of 1976):
In [24]: df.groupby('region')['Murder'].idxmax()
Out[24]:
region
North Central Michigan
Northeast New York
South Alabama
West Nevada
Name: Murder, dtype: object