此问题在此处已有答案:
How can I pivot a dataframe?(5个答案)
14天前关门了。
我有许多具有此形状的数据集:
| 用户|槽|问题|回答|
| --|--|--|--|
| 1 | 1 |Q1| A1|
| 1 | 2 |Q2| A2|
| 1 | 3 |Q3| A3|
| 999 | 1 |Q1| A1|
| 999 | 2 |Q2| A2|
| 999 | 3 |Q3| A3|
我想把table变成这个形状:
| 用户|问题1|答案1|问题2|答案2|
| --|--|--|--|--|
| 1 |Q1| A1| Q2|一个|
| 2 |Q2| A2| Q2|一个|
我试过使用pd.pivot()和不同的参数组合,得到的最接近的结果是
- 我将用户锁定在子 Dataframe 中
- 旋转子数据框
- 将透视表concat为一个包含所有子df的df
结果是这样的:
df_merged = pd.DataFrame()
for item in users:
sub_df = df.loc[df['username'] == item]
sub_df = sub_df.pivot(index='username',
columns='slot',
values=['questionsummary', 'responsesummary'])
df_merged = pd.concat([df_merged, sub_df])
字符串
| 用户|问题1|问题2|答案1|答案2|
| --|--|--|--|--|
| 1 |Q1| Q2| A1| A2|
| 2 |Q2| Q2| A1| A2|
| 999 |Q1| Q2| A1| A2|
我怎样才能使table具有所需的形状?
2条答案
按热度按时间u7up0aaq1#
试试这个:
字符串
yduiuuwa2#
pandas.DataFrame.pivot
是否会产生您想要的输出?字符串
输出如下所示:
的数据
为了匹配您的输出,我将在列中删除多级索引。为此:
型
现在
df_pivoted
看起来像这样:然后,为了匹配问答号码,我会做一些奇怪的事情:
型