【问题标题】:Groupby code with min_max year calculation具有 min_max 年份计算的 Groupby 代码
【发布时间】:2020-05-16 13:02:00
【问题描述】:

数据框:

Date               Code          
2019               ab            
2019               cd
2019               ab
2017               ab
2018               ab
2018               cd
2016               cd
2016               cd

输出:

Date               Code            Max_year_count-Min_year_count          
2019               ab              1        
2019               cd             -1
2019               ab              1
2017               ab              1
2018               ab              1
2018               cd             -1
2016               cd             -1
2016               cd             -1

目的是创建Max_year_count-Min_year_count 列。
例如,Code column ab(第 1 行)的计算:
(count of occurrence of code ab in max_year i.e 2019)-(count of occurrence of code ab in min_year i.e 2017) = 2-1 = 1

谢谢!!

【问题讨论】:

  • 不要认为2016年有ab
  • ab 在 2016 年不是强制性的。不同代码的最小和最大年份可能会有所不同,感谢 @sammywemmy,也编辑了我的问题
  • 您的DataFrame 只有一个2016 条目,但输出2 个2016。是笔误吗?
  • 是的错字,已修复,对此感到抱歉@Ch3steR

标签: python pandas dataframe group-by


【解决方案1】:

你可以试试这个。不是熊猫专家,可能存在更好的答案。这至少可以帮助您入门。

df.groupbypd.Index.maxpd.Index.min 一起使用

df
   Date Code
0  2019   ab
1  2019   cd
2  2019   ab
3  2017   ab
4  2018   ab
5  2018   cd
6  2016   cd
7  2016   cd

temp = df.groupby(['Code','Date']).size()
df['Max-Min']=df.Code.apply(lambda x:temp[x][temp[x].index.max()]-temp[x][temp[x].index.min()])

df
   Date Code  Max-Min
0  2019   ab        1
1  2019   cd       -1
2  2019   ab        1
3  2017   ab        1
4  2018   ab        1
5  2018   cd       -1
6  2016   cd       -1
7  2016   cd       -1

【讨论】:

    【解决方案2】:

    crosstabgroupbynth 函数的组合在这里可以提供帮助:

    #获取每年代码的频率计数

    res = (pd.crosstab(df.Code,df.Date)
           .stack()
            #this gets rid of entries for empty years
           .loc[lambda x: x.ne(0)]
          )
    
    #subtract first from last ... years are already sorted from min to max
    mapping = res.groupby('Code').nth(-1) - res.groupby('Code').nth(0)
    
    print(mapping)
    
    Code
    ab    1
    cd   -1
    dtype: int64
    
    df['Max_Min'] = df.Code.map(mapping)
    
    print(df)
    
        Date    Code    Max_Min
    0   2019    ab       1
    1   2019    cd      -1
    2   2019    ab       1
    3   2017    ab       1
    4   2018    ab       1 
    5   2018    cd      -1
    6   2016    cd      -1
    7   2016    cd      -1
    ​
    

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 1970-01-01
      • 2014-01-23
      • 1970-01-01
      • 2021-07-25
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      相关资源
      最近更新 更多