基于条件数据帧添加行

2024-05-20 19:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,如下所示:

enter image description here

我想根据以下逻辑添加新行:

  1. 添加“位置”为“舞台区域”的新行
  2. 此行是条目的总和,其中“位置”是“回复区-新商业区” 以及“地点”为“文化中心”的条目
  3. 把这些行放下 “位置”为“回复区-新商业区”和“文化区” “中心”

因此,对于2020年11月11日,我应该有以下条目:

enter image description here


Tags: 数据目的区域条目逻辑中心文化地点
3条回答

耶兹雷尔看起来很接近答案,但也许足球上的聚合是不正确的。。。只是看了他的代码,所以我可能错了

正确的版本如下所示,这与您在示例中建议的数字相匹配。 我制作了一个较小版本的示例表,用于测试。这里的“数据”是您的数据帧

mask = data["location"].isin(["Repley's Area - New Commercial Area", "Cultural Hub"])
data[mask].groupby(["day","locationTypes"], as_index=False)['dwell', 'football'].sum().assign(location="Stage Area")

输出:

          day locationTypes  dwell  football    location
0  2020-11-11          Zone    145      2307  Stage Area
1  2020-11-12          Zone     95      2905  Stage Area

谢谢你的回复!以下方面发挥了作用:

mask=df[df['location'].isin(["Repley's Area - New Commercial Area",'Cultural Hub'])]

df1=mask.groupby(['day','locationTypes'],as_index=False)['footfall','dwell (minutes)'].sum().assign(location='Stage Area')

#reordering the columns for pd.concat
df1= df1[df.columns]

df_final=pd.concat([df[~df['location'].isin(["Repley's Area - New Commercial Area",'Cultural Hub'])],df1]) 

#checking the result
df_final[(df_final['day']=='2020-11-11') & (df_final['location']=='Stage Area')]

#哪一个给了你

enter image description here

使用^{}按多个值进行筛选,聚合和添加列location,最后添加到原始数据帧,不使用掩码匹配行:

mask = df['location'].isin(["Reply's Area - New Commercial Area", 'Cultural Hub'])

df1 = (df[mask].groupby(['day','locationTypes'],as_index=False)[['dwell', 'football']]
              .sum()
              .assign(location = 'Stage Area')
              .reindex(df.columns, axis=1))

df = pd.concat([df[~mask], df1], ignore_index=True)

相关问题 更多 >