在 Pandas 数据框中循环以在每次迭代后添加一个新列

For loop within a Pandas dataframe to add a new column after each iteration

我有一个数据框,它在建筑物数据集上具有多种属性。这些建筑物都被分配到一个住宅组(公寓/半独立屋/独立屋/排屋)和一个小区域代码。这些建筑物也有建造年份列,但除了它们的小区域(大约 80 座建筑物)之外没有唯一标识符。

我想编写一个 for 循环,将这些建筑物分组到它们的住宅组中,然后将它们分解成它们的小区域,并分别为它们分配该小区域内该住宅组的中位建造年份。例如,划分小区域 12345 中的所有公寓,并分别(在新列中)分配该小区域公寓建设年份的中位数。

到目前为止 geo_dwelling 是一个包含列的 GeoDataFrame;

In [20]: geo_dwelling.head(5)

输出[20]: cso_small_area 都柏林邮政编码 建筑年份 建筑范围年份 住宅类型描述 能源评级 ... height_ag height_bg floors_ag floors_bg 类别住宅组 7101 268109005 DUBLIN 1 2009.0 2005 起 Mid floor apt. B3 ... 10.02 0 3 0 R 公寓 7101 268109005 DUBLIN 1 2009.0 2005 起 Mid floor apt. B3 ... 10.73 0 3 0 R 公寓 7101 268109005 DUBLIN 1 2009.0 2005 起 Mid floor apt. B3 ... 10.56 0 3 0 R 公寓 7101 268109005 DUBLIN 1 2009.0 2005 起 Mid floor apt. B3 ... 10.75 0 3 0 R 公寓 7101 268109005 DUBLIN 1 2009.0 2005 起 Mid floor apt. B3 ... 10.85 0 3 0 R 公寓

geo_dwelling = geo_dropped[
geo_dropped["Dwelling Group"].str.contains("Apartment", na=False)]

geo_dwelling.groupby(["cso_small_area"])[["Year of construction"]].median()

非常感谢任何帮助!

在 pandas 数据帧中创建 'for' 循环通常被认为是不好的做法(也需要很多时间!)。我相信您的问题的答案就在这篇文章中:

How to iterate over rows in a DataFrame in Pandas