在pandas DataFrame中基于其他列对一列求和

pgccezyw  于 2023-05-21  发布在  其他
关注(0)|答案(2)|浏览(174)

我在pandas DataFrame中有几列('SEC','DeviceName',' DAY '和' SPRAY')。我需要在“DAY”列中按“DeviceName”对每天的“SEC”求和,其中“SPRAY”== 1。
例如:

DeviceName       SEC     DAY     SPRAY
Applied_AA-6     1800    4       1
Applied_AA-6     600     4       0
Applied_AA-6     1373    5       1
Applied_AA-15    10      4       0
Applied_AA-15    1800    5       1
Applied_AA-15    13      5       1

结果应为:

Day 4   Day 5
Applied_AA-6     1800    1373
Applied_AA-15    0       1813
e5nqia27

e5nqia271#

使用groupbyunstack

df[df['SPRAY'].eq(1)].groupby(['DeviceName', 'DAY'])['SEC'] \
                     .sum() \
                     .unstack() \
                     .fillna(0)
DAY                 4       5
             
Applied_AA-15       0  1813.0
Applied_AA-6   1800.0  1373.0
lvjbypge

lvjbypge2#

另一种可能的解决方案,基于pandas.pivot_table

(df[df['SPRAY'].eq(1)]
 .pivot_table(
     index='DeviceName', columns='DAY', values='SEC', 
     aggfunc='sum', sort=False, fill_value=0)
 .rename_axis(None, axis=1).reset_index())

输出:

DeviceName     4     5
0   Applied_AA-6  1800  1373
1  Applied_AA-15     0  1813

相关问题