簡體   English   中英

根據列的值計算記錄

[英]Count the records based on value of columns

我有以下 df:

ID  Col1 Col2 Col3
1    A    NB    C
2    A    NB    C 
3    NS   B     NC
4    NS   NB    NC
5    NS   B     NC
6    NS    B     C

我正在嘗試根據它們的值獲取每列的計數。

Col1 中有多少個“A”

Col2 中有多少個“B”

Col3 中有多少個“C”

在原來的df中我有很多專欄和條件。

預期的 output:

Col1                Col2            Col3         
TotalCount"A"   TotalCount"B"    TotalCount"C"

所以,我試圖獲取列列表並對其進行迭代,但沒有得到預期的結果。 我在 jupyternotebook 中使用 pandas

您可以在此處使用df.eq並傳遞要比較的值列表。

values = ['A', 'B', 'C']
out = df.loc[:, 'Col1':].eq(values).sum()

Col1    2
Col2    3
Col3    3
dtype: int64

擴展@Ch3ster 的答案以匹配預期的 output:

In [1382]: values = ['A', 'B', 'C']
In [1391]: res = df.filter(like='Col', axis=1).eq(values).sum().to_frame().T

In [1392]: res
Out[1392]: 
   Col1  Col2  Col3
0     2     3     3

暫無
暫無

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

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