gpt4 book ai didi

python - 并排打印多列的 Python 字典作为 Pandas value_counts

转载 作者:行者123 更新时间:2023-12-04 08:49:09 27 4
gpt4 key购买 nike

我是 Python、Numpy 和 Pandas 数据科学的新手。所以,如果我的问题很微不足道,请原谅。
有没有办法从 Python 字典中打印任意两列或更多列的 value_counts?
例如,现在我只是打印我想要的列的 value_counts,如下所示:

import os
import numpy as np
import pandas as pd
import matplotlib as plot

dict_h = {'a':['APPLE', 'DONUT', 'APPLE', 'APPLE', 'APPLE', 'DONUT', 'PEAR'],
'b':['PEAR', 'DONUT', 'DONUT', 'DONUT', 'APPLE', 'PEAR', 'DONUT'],
'c':['APPLE', 'APPLE', 'APPLE','DONUT','DONUT','DONUT','PEAR'],
'd':['PEAR', 'PEAR', 'PEAR','DONUT','DONUT','DONUT','PEAR']}

print('\n')
print('Orignal Dict:')
print(dict_h)
y = pd.DataFrame.from_dict(dict_h, orient='index')
print('\n')
print(y.describe())
print('\n')
print(y[0].value_counts())
print('\n')
print(y[1].value_counts())
那打印:
...
PEAR 2
APPLE 2
Name: 0, dtype: int64


DONUT 2
PEAR 1
APPLE 1
Name: 1, dtype: int64
但相反,我希望像这样使用打印:
         0    1   
-------------
APPLE 2 1
PEAR 2 1
DONUT NaN 2
-------------
谢谢你。
德鲁

最佳答案

要获得所需的输出,请使用 transposemeltcrosstab :

s = df.T.melt()

print (pd.crosstab(s["value"], s["variable"]))

variable 0 1 2 3 4 5 6
value
APPLE 2 1 2 1 2 0 0
DONUT 0 2 1 3 2 3 1
PEAR 2 1 1 0 0 1 3

关于python - 并排打印多列的 Python 字典作为 Pandas value_counts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64165878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com