首页 > 解决方案 > 如何正确旋转熊猫数据框

问题描述

我有以下数据框:

df = pd.DataFrame([{'answers': ['No'], 'questionId': 'applicationSubmitted'}, {'answers': ['NOT_READY_TO_ENROLL'], 'questionId': 'status'}, {'answers': ['Intro'], 'questionId': 'salesProcessReached'}, {'answers': [True], 'questionId': 'noTimeToCoverCurrentPlan'}, {'answers': [''], 'questionId': 'currentPlan'}, {'answers': ['No'], 'questionId': 'scheduleFollowUp'}])

应用数据透视函数后df.pivot(columns='questionId'),我得到下表: 多余的行太多

如何调整枢轴以使所有答案仅显示 1 行,标题仅显示 1 行而不是 2 行。

谢谢

标签: pythonpandasdataframepivotpivot-table

解决方案


pivot_tableaggfuncas一起使用max

df.pivot_table(columns='questionId', aggfunc=max)

输出:

questionId applicationSubmitted currentPlan noTimeToCoverCurrentPlan salesProcessReached scheduleFollowUp                 status
answers                    [No]          []                   [True]             [Intro]             [No]  [NOT_READY_TO_ENROLL]

推荐阅读