![](/img/trans.png)
[英]How to count the number of occurrences based on uniques values in another columns dataframe in pandas? Please Consider the below example
[英]How to count occurrences of a set of values for a range of columns in a pandas dataframe?
我有一個熊貓數據框,看起來像這樣:
數據幀填充有4個不同的字符串: '00', '01', '10',
和'11'
。 我希望對每列中值的每次出現進行計數,以便上面的數據將返回一個看起來像這樣的結果數據框:
A B C D E
00 2 1 3 0 3
01 2 2 0 2 1
10 0 0 1 2 0
11 1 2 1 1 1
可以使用以下代碼創建原始數據框:
dft = pd.DataFrame({'A' : ['11', '01', '01', '00', '00'],
'B' : ['00', '01', '11', '01', '11'],
'C' : ['00', '00', '10', '00', '11'],
'D' : ['10', '01', '11', '10', '01'],
'E' : ['00', '01', '00', '11', '00'],})
dft
您可以將value_counts
與字典理解一起使用來生成值,然后使用數據來創建DataFrame。
>>> pd.DataFrame({col: dft[col].value_counts() for col in dft}).fillna(0)
A B C D E
00 2 1 3 0 3
01 2 2 0 2 1
10 0 0 1 2 0
11 1 2 1 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.