簡體   English   中英

計算 A 列中相同值的 B 列 value_counts

[英]Count column B value_counts for same values in column A

對於下面的輸入數據框,我們要創建兩列,A_count 和 B_count。

有一個名為 around_row_num 的輸入變量。 IE for around_row_num=2,我們要查看當前行之前2行和之后2行,並計算與當前行具有相同'ID'的'Label'列中'A'的出現次數。

輸入:

import pandas as pd

df = pd.DataFrame({'ID': [1, 1, 1, 1, 2, 2],'Label': ['A', 'A', 'B', 'B', 'A', 'B']})
    
   ID Label
0   1     A
1   1     A
2   1     B
3   1     B
4   2     A
5   2     B

around_row_num=2 的輸出:

        ID  Label A_count B_count 
        1   A     2        1
        1   A     2        1
        1   B     1        2
        1   B     0        2        
        2   A     1        1
        2   B     1        1       

謝謝!

更新到來自 ID 組的帳戶:

df.set_index([df['ID'], 'Label'], append=True)['ID'].unstack()\
  .groupby('ID', as_index=False, group_keys=False)\
  .rolling(3, center=True).count()

輸出:

Label    A    B
  ID           
0 1    2.0  0.0
1 1    2.0  1.0
2 1    1.0  2.0
3 1    0.0  2.0
4 2    1.0  1.0
5 2    1.0  1.0

嘗試這個:

df.set_index('Label', append=True)['ID'].unstack().rolling(3, center=True).count()

輸出:

Label    A    B
0      2.0  0.0
1      2.0  1.0
2      1.0  2.0
3      1.0  2.0
4      1.0  2.0
5      1.0  1.0

暫無
暫無

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

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