Skip to main content
 首页 » 编程设计

python之遍历 Pandas Dataframe 以根据条件进行计算

2025年02月15日10youxin

对于下面的 DataFrame,我需要为每年和每月创建一个新列“unit_count”,即“unit”/“count”。但是,由于每年和每月都不是唯一的,对于每个条目,我只想使用 B 选项中给定月份的计数。

key UID count   month   option  unit    year 
0   1   100     1       A       10      2015 
1   1   200     1       B       20      2015 
2   1   300     2       A       30      2015 
3   1   400     2       B       40      2015 

本质上,我需要一个执行以下操作的函数:

unit_count = df.unit / df.count 

对于单位值,但仅使用给定“月份”中选项“B”的“计数”值。

因此最终结果将如下表所示,其中 unit_count 将单位数除以给定月份“扇区”“B”的计数。

key UID count   month   option  unit    year    unit_count 
0   1   100     1       A       10      2015    0.05 
1   1   200     1       B       20      2015    0.10 
2   1   300     2       A       30      2015    0.075 
3   1   400     2       B       40      2015    0.01 

这是我用来创建原始 DataFrame 的代码:

df = pd.DataFrame({'UID':[1,1,1,1], 
                'year':[2015,2015,2015,2015], 
                'month':[1,1,2,2], 
                'option':['A','B','A','B'], 
                'unit':[10,20,30,40], 
                'count':[100,200,300,400] 
                }) 

请您参考如下方法:

看来你可以先创建 NaN where not option is B 然后再除以填充的 NaN 值:

注意:DataFrame 必须按year、month 和option 从前到后排序每个组的 B 值

#if necessary in real data 
#df.sort_values(['year','month', 'option'], inplace=True) 
 
df['unit_count'] = df.loc[df.option=='B', 'count'] 
print (df) 
   UID  count  month option  unit  year  unit_count 
0    1    100      1      A    10  2015         NaN 
1    1    200      1      B    20  2015       200.0 
2    1    300      2      A    30  2015         NaN 
3    1    400      2      B    40  2015       400.0 
 
df['unit_count'] = df.unit.div(df['unit_count'].bfill()) 
print (df) 
   UID  count  month option  unit  year  unit_count 
0    1    100      1      A    10  2015       0.050 
1    1    200      1      B    20  2015       0.100 
2    1    300      2      A    30  2015       0.075 
3    1    400      2      B    40  2015       0.100