首页 > 解决方案 > 对于 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 但这不是一个可接受的解决方案,因为它过于复杂并且不遵守欧姆定律,因为我正在学习的课程是针对数据科学的,因此效率是原则。

标签: pandasdataframe

解决方案


如果我正确理解您想要什么,您可以使用以下两种方法之一:

  1. 方法:保持你的循环(不推荐看这篇文章):
for i in range(1995, 2022, 1):
    temp = df[df['Year'] == i]
    yr_max = temp[temp['Average_price'] == temp['Average_price'].max()]
  1. 方法(使用 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

推荐阅读