简体   繁体   中英

Function equivalent of Excel's SUMIFS()

I have a sales table with columns item , week , and sales . I wanted to create a week to date sales column ( wtd sales ) that is a weekly roll-up of sales per item.

I have no idea how to create this in Python.

I'm stuck at groupby() , which probably is not the answer. Can anyone help?

output_df['wtd sales'] = input_df.groupby(['item'])['sales'].transform(wtd)

As I stated in my comment, you are looking for cumsum() :

import pandas as pd

df = pd.DataFrame({
    'items': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
    'weeks': [1, 2, 3, 4, 1, 2, 3, 4],
    'sales': [100, 101, 102, 130, 10, 11, 12, 13]
})

df.groupby(['items'])['sales'].cumsum()

Which results in:

0    100
1    201
2    303
3    433
4     10
5     21
6     33
7     46
Name: sales, dtype: int64

I'm using:

pd.__version__
'1.5.1'
 

Putting it all together:

import pandas as pd

df = pd.DataFrame({
    'items': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
    'weeks': [1, 2, 3, 4, 1, 2, 3, 4],
    'sales': [100, 101, 102, 130, 10, 11, 12, 13]
})

df['wtds'] = df.groupby(['items'])['sales'].cumsum()

Resulting in:

  items  weeks  sales  wtds
0     A      1    100   100
1     A      2    101   201
2     A      3    102   303
3     A      4    130   433
4     B      1     10    10
5     B      2     11    21
6     B      3     12    33
7     B      4     13    46 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM