我正在尝试根据其周数来计算数据框特定子集的变化百分比。数据框如下所示:
ref_dt week_name county_name state_name county_fips_code cmi
0 2020-01-01 2020-W01 Broward Florida 12011 3.651278
1 2020-01-02 2020-W01. Broward Florida 12011 3.851842
2 2020-01-03 2020-W01. Broward Florida 12011 3.868523
3 2020-01-04 2020-W01. Broward Florida 12011 3.748446
4 2020-01-05 2020-W01. Broward Florida 12011 3.650769
5 2020-01-06 2020-W02. Broward Florida 12011 3.878860
6 2020-01-07 2020-W02. Broward Florida 12011 3.899171
7 2020-01-08 2020-W02. Broward Florida 12011 3.907816
8 2020-01-09 2020-W02. Broward Florida 12011 3.913623
9 2020-01-10 2020-W02. Broward Florida 12011 3.919010
它具有佛罗里达州每个县的信息(此处仅以布劳沃德为例),并且在cmi列中计算了流动性指数。通过将一周中某天的移动量(ref_dt)与一周中同一天的平均值进行比较来计算百分比变化。这是我在熊猫中进行次选择后的第1周和Broward的示例。
df = counties[counties['county_name']=='Broward']
week1 = df[df['week_name'] == '2020-W01']
cmi_mean = week1['cmi'].mean()
week1['percent_change'] = week1['cmi']/cmi_mean * 100
csv的最终输出看起来像这样(我删除了state和county_fips_code):
ref_dt week_name county_name cmi percent_change
0 2020-01-01 2020-W01 Broward 3.651278 97.259216
1 2020-01-02 2020-W01 Broward 3.851842 102.601642
2 2020-01-03 2020-W01 Broward 3.868523 103.045989
3 2020-01-04 2020-W01 Broward 3.748446 99.847497
4 2020-01-05 2020-W01 Broward 3.650769 97.245656
我想为每个县(每周1到14)应用相同的逻辑。最好的方法是什么?我是否需要使用数据透视表或堆栈重塑数据框并根据它们的week_name每周创建列,还是可以计算数据框当前结构的变化百分比?
注意:必须每周计算每个平均值。
答案 0 :(得分:0)
将df.groupby
与transform
一起使用,并让熊猫使用索引来处理计算对齐:
df['percent_change'] = df['cmi'] / df.groupby(['county_name', 'week_name'])['cmi'].transform('mean') * 100
输出:
ref_dt week_name county_name state_name county_fips_code cmi percent_change
0 2020-01-01 2020-W01. Broward Florida 12011 3.651278 97.259220
1 2020-01-02 2020-W01. Broward Florida 12011 3.851842 102.601650
2 2020-01-03 2020-W01. Broward Florida 12011 3.868523 103.045982
3 2020-01-04 2020-W01. Broward Florida 12011 3.748446 99.847487
4 2020-01-05 2020-W01. Broward Florida 12011 3.650769 97.245661
5 2020-01-06 2020-W02. Broward Florida 12011 3.878860 99.363782
6 2020-01-07 2020-W02. Broward Florida 12011 3.899171 99.884084
7 2020-01-08 2020-W02. Broward Florida 12011 3.907816 100.105541
8 2020-01-09 2020-W02. Broward Florida 12011 3.913623 100.254297
9 2020-01-10 2020-W02. Broward Florida 12011 3.919010 100.392295