简体   繁体   中英

Calculation based on feature in DataFrame in Python Pandas?

I have DataFrame like below:

df = pd.DataFrame({"ID" : ["1", "2", "2", "1", "3"],
                    "currency" : ["GBP", "GBP", "GBP", "CHF", "EUR"],
                    "amount" : [100, 200, 300, 400, 500]})

And I need to calculate:

  1. New1 = Number of agreements with GBP currency
  2. New2 = Amount of agreement with GBP currency

I need result like below:

在此处输入图像描述

We can do filter then groupby and reindex

out = df.loc[df.currency=='GBP'].groupby(['ID']).amount.agg(['count','sum']).reindex(df.ID.unique())
Out[210]: 
    count    sum
ID              
1     1.0  100.0
2     2.0  500.0
3     NaN    NaN

You can try this -

import pandas as pd

df = pd.DataFrame({"ID" : ["1", "2", "2", "1", "3"],
                    "currency" : ["GBP", "GBP", "GBP", "CHF", "EUR"],
                    "amount" : [100, 200, 300, 400, 500]})

>>> pd.pivot_table(df.loc[df.currency=='GBP'],index=["ID"],aggfunc={'currency':'count','amount':'sum'}).reindex(df.ID.unique()).reset_index()
   
ID  amount  currency                
1    100.0       1.0
2    500.0       2.0
3      NaN       NaN

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