python - 如何计算 pandas 数据框中一系列列的一组值的出现次数?

标签 python pandas dataframe

我有一个 pandas 数据框,看起来像这样:

matrix

数据框填充了 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

关于python - 如何计算 pandas 数据框中一系列列的一组值的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35185944/

相关文章:

python - dir_util.copy_tree 在 shutil.rmtree 之后失败

python - 计数是否在多个索引数据框中

python - 从字典中打印单个唯一行而不重复

python - Pandas Dataframe 中值的就地更新

python - 在 Pandas 数据框中合并具有相同浮点索引的行

python - tensorflow-gpu 中的 "' CXXABI_1.3.8 ' not found"- 从源安装

python - 使用 python-xbee 向远程 Xbee 发送远程 AT 命令

python - 尝试卡住 python 应用程序时未找到 Google Protocol Buffer

python - 如何将填充的 0 行添加到 Pandas 数据框?

python - Pandas:如何将新列附加到数据框中的所有行