简体   繁体   English

如何计算熊猫数据框中一系列列的一组值的出现?

[英]How to count occurrences of a set of values for a range of columns in a pandas dataframe?

I have a pandas dataframe that looks something like this: 我有一个熊猫数据框,看起来像这样:

矩阵

The dataframe is populated with 4 distinct strings: '00', '01', '10', and '11' . 数据帧填充有4个不同的字符串: '00', '01', '10','11' I'm hoping to count each occurrence of the values in each column, so that the data above would return a resulting dataframe that looks something like this: 我希望对每列中值的每次出现进行计数,以便上面的数据将返回一个看起来像这样的结果数据框:

    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

The original dataframe can be created with this code: 可以使用以下代码创建原始数据框:

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

You can use value_counts together with a dictionary comprehension to generate the values, and then use the data to create a DataFrame. 您可以将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.

相关问题 如何根据 pandas 中另一列 dataframe 中的唯一值计算出现次数? 请考虑以下示例 - 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 in a dataframe columns? Pandas计算数据帧中不同列上的所有匹配项 - Pandas count all occurrences on different columns in a dataframe 使用pandas计算给定集合中行值的出现次数 - Count occurrences of row values in a given set with pandas 如何计算出现在2个或更多数据框列中的出现次数? - How to count occurrences that appear in 2 or more dataframe columns? 如何计算 pandas dataframe 中一系列单元格中 2 个值以内的单元格? - How to count cells that are within 2 values, in a range of cells in a pandas dataframe? 如何使用Pandas isin()来测试数据框中一系列列的值 - How to use pandas isin() to test values on a range of columns in a dataframe 快速计算pandas DataFrame中所有值的出现次数 - Fast way to count occurrences of all values in a pandas DataFrame 如何计算熊猫数据框中各列的非NaN值? - How to count non NaN values accross columns in pandas dataframe? 如何计算各列中的更改值 - Pandas Dataframe - How to count changing values across various columns - Pandas Dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM