簡體   English   中英

根據其他列的分組依據和條件創建新列

[英]Creating a new column based on a group-by and condition of other columns

我正在使用 dataframe 設置如下:

| date | Product | Region | Age |

| 01/12/20 | Sales | NW | 17 |
| 01/12/20 | Sales | NW | 30 |
| 01/11/20 | Sales | SW | 32 |
| 01/12/20 | Import | SW | 5 |
| 01/12/20 | Import | SW | 45 |
| 01/12/20 | Sales | NW | 31 |
| 01/12/20 | Import | NW | 2 |

我想創建一個新的 dataframe 顯示年齡 > 30 的行數,這些行數按日期/產品/區域分組。 IE:

日期 產品 地區 陳年
01/12/20 銷售量 西北 2
20 年 1 月 11 日 銷售量 西南 1
01/12/20 進口 西南 1

我嘗試了許多不同的方法,最新的使用 lambda 但到目前為止不成功:

df['aged'] = df.groupby([pd.Grouper(freq="M"), 'Product', 'Region'])['Product'].transform(lambda x: count( x ) if df['age'] >= 30 else 0)

有沒有人能夠幫助並告訴我我哪里出錯了?

我認為你需要:

new_df = (df[df['Age'].ge(30)].groupby(df.columns.difference(['Age']).tolist())['Age']
                              .count()
                              .reset_index(name='aged'))
print(new_df)


  Product Region      date  aged
0  Import     SW  01/12/20     1
1   Sales     NW  01/12/20     2
2   Sales     SW  01/11/20     1

請試試:

df[df['Age'].ge(30)].groupby(['date', 'Product', 'Region'])\
['Age'].count().to_frame('aged')



                         aged
date     Product Region      
01/11/20 Sales   SW         1
01/12/20 Import  SW         1
         Sales   NW         2

已經提出的答案的替代方案:

在我看來,最簡單的方法是在分組之前進行過濾,就像其他人一樣; 我偏離的地方是使用as_index=False ,並使用size進行聚合:

(df.loc[df.Age.ge(30)]
  .groupby(["date", "Product", "Region"], sort = False, as_index=False)
  .agg(Aged=("Age", "size"))
)


    date    Product Region  Aged
0   01/12/20    Sales   NW  2
1   01/11/20    Sales   SW  1
2   01/12/20    Import  SW  1

這個使用了 groupby,其中 boolean 條件包含在 groupby 中:

(df.groupby(["date", "Product", "Region", df.Age.ge(30)], sort = False)
  .size()
  .drop(False, level="Age")
  .droplevel("Age")
  .reset_index(name="Aged")
 )

另一種選擇是使用交叉表,再次使用 boolean 條件:

(pd.crosstab([df.date, df.Product, df.Region], df.Age.ge(30))
   .iloc[:, -1]
   .loc[lambda x: x != 0]
   .reset_index(name='Aged'))

    date    Product Region  Aged
0   01/11/20    Sales   SW  1
1   01/12/20    Import  SW  1
2   01/12/20    Sales   NW  2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM