簡體   English   中英

Python:按組計數 dataframe 中的特定事件

[英]Python: Counting specific occurrences in dataframe by group

假設我有一個df:

df = pd.DataFrame({'id': [12, 35, 37, 67, 99, 78],
                  'product': ['banana', 'apple', 'banana', 'pear', 'banana', 'apple'],
                  'reordered': [1, 0, 0, 1, 1, 1]})


    id     product   reordered
0   12     banana    1
1   35     apple     0
2   37     banana    0
3   67     pear      1
4   99     banana    1
5   78     apple     1

我想計算“產品”列中產品的出現次數,以及按產品分組的“重新排序”列中的值。 期望的結果:

       product   count   reordered_0   reordered_1
   0   banana    3       1             2
   1   apple     2       1             1
   2   pear      1       1             0

請指教

使用帶有DataFrame.insertcrosstab作為第一個 position 的列:

df = pd.crosstab(df['product'], df.reordered).add_prefix('reordered_')
df.insert(0, 'count', df.sum(axis=1))
df = df.reset_index().rename_axis(None, axis=1)
print(df)
  product  count  reordered_0  reordered_1
0   apple      2            1            1
1  banana      3            1            2
2    pear      1            0            1

讓我們嘗試使用crosstab

(pd.crosstab(df['product'], df['reordered'])
   .add_prefix('reordered_')
   .assign(count=lambda x: x.sum(1))
   .reset_index()
)

Output:

reordered product  reordered_0  reordered_1  count
0           apple            1            1      2
1          banana            1            2      3
2            pear            0            1      1

暫無
暫無

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

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