LonelySoul
LonelySoul

Reputation: 1232

Groupby Clause in Pandas

I am trying to find the GroupBy Clause (in PANDAS DATAFRAME) which can do following things.

  1. InPlace Transformation.
  2. Add All the Money
  3. If possible then to get the Original Dataframe with Columns "A" and "Money", And not "A" as index and "Money" as column.

The input is like below.

dataframe = pandas.DataFrame({'A':[11,11,22,22],
                              'Cust':['C','D','C','C'],
                              'Money':np.arange(10,30,5)})

Now I wanted to add / subtract Money column based on Type of Cust. Like if its "C" then subtract while "D" then add and rolled to the column "A". So for this example it will be

For A as in "11" Money is "5" For B as in "22" Money is "-45"

Upvotes: 1

Views: 677

Answers (1)

Dan Allan
Dan Allan

Reputation: 35265

Starting with your example

In [16]: df
Out[16]: 
    A Cust  Money
0  11    C     10
1  11    D     15
2  22    C     20
3  22    C     25
  1. Set the sign of Money based on whether Cust is C or D, as you describe.

    In [17]: df['Money'][df['Cust'] == 'C'] *= -1
    
  2. Sum the money, grouped by the column 'A'.

    In [18]: df.groupby('A').sum()
    Out[18]: 
        Money
    A        
    11      5
    22    -45
    
  3. Run In [17] again to restore your original DataFrame, intact.

Upvotes: 2

Related Questions