Python3.6:创建一个数据透视表,汇总dataframe中多列的值计数
我有以下数据框:Python3.6:创建一个数据透视表,汇总dataframe中多列的值计数,python,pandas,dataframe,pivot-table,python-3.6,Python,Pandas,Dataframe,Pivot Table,Python 3.6,我有以下数据框: df = pd.DataFrame({'X': ['Agree', 'Disagree', 'Agree', 'Neutral', 'Agree','Neutral'], 'Y': ['Disagree', 'Neutral', 'Agree', 'Disagree', 'Agree', 'Neutral'], 'Z': ['Agree', 'Neutral', 'Neutral', 'Disagree', 'Neu
df = pd.DataFrame({'X': ['Agree', 'Disagree', 'Agree', 'Neutral', 'Agree','Neutral'],
'Y': ['Disagree', 'Neutral', 'Agree', 'Disagree', 'Agree', 'Neutral'],
'Z': ['Agree', 'Neutral', 'Neutral', 'Disagree', 'Neutral','Neutral']})
我想创建一个表格,汇总每个类别(列)X、Y和Z的“同意”、“中立”和“不同意”数量
输出应如下所示:
df_answer = pd.DataFrame({'Response': ['Agree', 'Neutral', 'Disagree'],
'X': [3,2,1],
'Y': [2,2,2],
'Z': [1,4,1]})
我试图找到一个答案,但似乎找不到一个特别解决这个问题
我希望有一个单独的索引,但如果“响应”是索引也可以,如果这样做更容易的话。我不知道如何使用透视表来实现这一点,但如果它有帮助的话,这可以很容易地实现,而无需:
out = pd.DataFrame()
for col in df.columns:
out = out.append(df[col].value_counts())
out = out.transpose()
X Y Z
Agree 3.0 2.0 1.0
Disagree 1.0 2.0 1.0
Neutral 2.0 2.0 4.0
如果需要,您还可以根据索引命名“响应”列我们可以使用+pd.value\u计数
:
new_df=df.apply(pd.value_counts)
print(new_df)
X Y Z
Agree 3 2 1
Disagree 1 2 1
Neutral 2 2 4
我们还可以做到:
df2=df.melt()
new_df=pd.crosstab(df2['value'],df2['variable'])
print(new_df)
variable X Y Z
value
Agree 3 2 1
Disagree 1 2 1
Neutral 2 2 4
谢谢,德里克,很好用。感谢如此快速的响应:)这就得到了解决方案,但使用循环不是一个好主意。对于大型数据集,它可能会导致计算量大。但这是一个很好的快速修复方法,也是用更复杂(非标准)的功能和逻辑填充空数据帧的基础。这不是最佳的解决方案,这是一个解决方案,如果工作,并不是关键,然后继续前进,非常感谢。有很多方法可以做到这一点!非常感谢您的时间和帮助:)