【问题标题】:Calculation based on feature in DataFrame in Python Pandas?基于 Python Pandas 中 DataFrame 中的特征的计算?
【发布时间】:2021-04-02 04:15:06
【问题描述】:

我有如下数据框:

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

我需要计算:

  1. New1 = 使用英镑货币的协议数量
  2. New2 = 与英镑货币的协议金额

我需要如下结果:

【问题讨论】:

    标签: python pandas dataframe aggregation


    【解决方案1】:

    我们可以过滤然后groupbyreindex

    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
    

    【讨论】:

      【解决方案2】:

      你可以试试这个-

      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
      
      

      【讨论】:

        猜你喜欢
        • 2021-03-27
        • 2013-01-15
        • 2020-05-17
        • 2021-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多