pandas - 对于 Pandas DataFrame,我如何访问在一列中具有特定值的行?
问题描述
因此,我有一个包含伦敦所有行政区的数据框,以及 1995 年至 2021 年期间的平均房价。
我要做的是编译一个新的数据框,该数据框每年都会占用最昂贵的自治市镇。
原始 df 的列名是:[London_Borough, ID, Average_price, Year]
起初,我想我可以每年循环并创建一个临时 df,在其中分配每个行政区及其特定年份的价格,然后从那里提取平均价格的最大值。
例如:
for i in range(1995, 2022, 1):
temp = df[df['Year'] == i]
yr_max = temp['Average_price'].max()
这样做的问题是,虽然我得到了那一年最昂贵的自治市镇,但我所拥有的只是没有与之相关的相应自治市镇的数字。
有什么办法可以提取整行吗?或者至少只是自治市镇和价格?
老实说,这可能只是一个简单的语法问题,但我已经浏览了我的笔记和在线资源,但找不到给定一列的特定值来定位行的方法。
我能想到的唯一解决方案是首先重置临时 df 的索引,然后创建当年的平均价格列表,遍历列表直到它与最高价格匹配,然后使用该列表的索引来定位索引临时 df 但这不是一个可接受的解决方案,因为它过于复杂并且不遵守欧姆定律,因为我正在学习的课程是针对数据科学的,因此效率是原则。
解决方案
如果我正确理解您想要什么,您可以使用以下两种方法之一:
- 方法:保持你的循环(不推荐看这篇文章):
for i in range(1995, 2022, 1):
temp = df[df['Year'] == i]
yr_max = temp[temp['Average_price'] == temp['Average_price'].max()]
- 方法(使用 pandas 内置方法):
df.iloc[df.groupby(['Year'])['Average_price'].idxmax()]
例如使用以下输入:
Year Average_price london_borough
0 1999 1320 Barnet
1 1999 810 Enfield
2 1999 2250 Ealing
3 2000 1524 Bexley
4 2000 810 Camden
5 2000 1524 Brent
6 2001 1524 Barnet
7 2001 2540 Barnet
8 2001 810 Ealing
9 2002 1524 Camden
10 2002 3000 Ealing
11 2002 1524 Brent
你会得到输出:
>>> print(df.iloc[df.groupby(['Year'])['Average_price'].idxmax()])
Year Average_price london_borough
2 1999 2250 Ealing
3 2000 1524 Bexley
7 2001 2540 Barnet
10 2002 3000 Ealing
如果您想访问特定年份,您可以执行以下操作:
>>> yr_max = df.iloc[df.groupby(['Year'])['Average_price'].idxmax()]
>>> yr_max[yr_max['Year'] == 1999]
Year Average_price london_borough
2 1999 2250 Ealing
推荐阅读
- c# - 如何在 Unity 中使用原生 android 文件打开对话框?
- visual-studio - 如何自动应用 VS 快速操作提供的解决方案来解决 Stylecop(roslyn) 代码样式错误
- android - onCharacteristicRead 返回状态 137
- cuda - cudaMemcpyToSymbol 给出 cudaErrorUnknown
- google-sheets - 如何从一个谷歌表同步不同的多个日历?
- ruby - Logstash 过滤掉嵌套 json 数组中键的空值
- javascript - React Formik 复选框组不会变成单个选中或未选中元素的数组
- android - NestedWebView 与 ScrollingViewBehavior 一起正常工作
- html - 增加屏幕高度时,子块必须超出父块
- angular - 角度动作取决于其他函数 http 结果的结果