【问题标题】:groupby with multiple conditionsgroupby 有多个条件
【发布时间】:2020-11-27 12:16:27
【问题描述】:
df  fruit  year sale  important
0   apple  2010  
1   apple  2011
2   apple  2012
3   apple  2013
4   apple  2014 True    Yes
5   apple  2015 True
6   apple  2017 True
7   apple  2018 True
7   apple  2019 
8   apple  2020 True    Yes
9   banana 2010
...

如何生成“重要”列?

是的,如果每个水果: (1) 当年有销售, (2) 前一年没有销售,并且 (3) 该年与上一个“重要”年之间至少有 3 年的差距。

【问题讨论】:

  • 你能提供数据作为字典吗
  • 我尝试了 df.to_dict() 但似乎无法正常工作
  • @asd 每个fruit 的所有年份是否都按顺序存在?
  • 是的,df 是按水果和年份排序的(即从旧年份到最近年份)

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

如果这适用于您的情况,请尝试。假设 df 按水果和年份排序。

for i in df['fruit'].unique():
    df1 = df[(df['sale'] == 'True') & (df['sale'].shift() != 'True') & (df['fruit'] == i)]
    df1 = df1[(df1['year'].diff() >=3) | (df1['year'].diff().fillna(0) == 0)]
    df.loc[df.index.isin(df1.index), 'important'] = 'Yes'

打印:

    fruit   year    sale    important
0   apple   2010    None    NaN
1   apple   2011    None    NaN
2   apple   2012    None    NaN
3   apple   2013    None    NaN
4   apple   2014    True    Yes
5   apple   2015    True    NaN
6   apple   2017    True    NaN
7   apple   2018    True    NaN
8   apple   2019    None    NaN
9   apple   2020    True    Yes
10  banana  2010    True    NaN

我测试了几个随机组合的水果和年份,并且正在尽我所能检查。

【讨论】:

  • 您介意解释一下df.index.isin(df1.index) 的工作原理吗?
  • 当然。 df1 包含匹配所有三个条件的所有元素。现在将 df1 绑定到原始 df。我正在使用isin 命令匹配 df 和 df1 的索引,并调用一个名为“重要”的新列作为“是”,用于那些返回 True 的匹配项。
  • 我不得不使用它,df1['year'].diff().fillna(0) == 0 因为,第一个差异总是返回 NaN 的差异,因为它没有以前的真实值可供比较。例如,您的示例中的 apple 2014 True 没有以前的比较“重要”的年份,因此其上的 .diff() 将返回为 NaN,我将其转换为零,并默认使用 df1['year'].diff().fillna(0) == 0
猜你喜欢
  • 2022-01-23
  • 2021-04-06
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 2012-02-28
  • 2018-06-20
  • 2020-05-31
  • 2019-04-04
相关资源
最近更新 更多