为Pandas数据透视表选择参数时出现问题[重复]

ryoqjall  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(115)

此问题在此处已有答案

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具有所需的形状?

u7up0aaq

u7up0aaq1#

试试这个:

df = pd.DataFrame({'user': [1, 1, 1, 999, 999, 999],
                  'slot': [1, 2, 3, 1, 2, 3],
                   'question': ['Q1', 'Q2', 'Q3', 'Q1', 'Q2', 'Q3'],
                   'answer': ['A1', 'A2', 'A3', 'A1', 'A2', 'A3']})
smin = min(df['slot'])
smax = max(df['slot'])+1
df = pd.DataFrame(df.pivot(index='user',
                           columns='slot',
                           values=['question', 'answer']))

col_new =['user']
for i in range(0, len(df.columns)):
    col_new.append(df.columns[i][1])
    
df = pd.DataFrame(df.to_records())
df.columns = col_new

df = df[['user']+list(range(smin, smax))]
print(df)

   user   1   1   2   2   3   3
0     1  Q1  A1  Q2  A2  Q3  A3
1   999  Q1  A1  Q2  A2  Q3  A3

字符串

yduiuuwa

yduiuuwa2#

pandas.DataFrame.pivot是否会产生您想要的输出?

import pandas as pd

df = pd.DataFrame({"user": [1, 1, 1, 2, 2, 2],
      "slot": [1, 2, 3, 1, 2, 3],
      "question" : ['Q1', 'Q2', 'Q3', 'Q1', 'Q2', 'Q3'],
      "answer" : ['A1', 'A2', 'A3', 'A1', 'A2', 'A3']
     })

df_pivoted = df.pivot(index = 'user', columns='slot', values= ['question', 'answer'])

字符串
输出如下所示:


的数据
为了匹配您的输出,我将在列中删除多级索引。为此:

cols = ['_'.join((pair[0], str(pair[1]))) for pair in df_pivoted.columns]
df_pivoted.columns = cols


现在df_pivoted看起来像这样:

然后,为了匹配问答号码,我会做一些奇怪的事情:

desired_order = [x[::-1] for x in df_pivoted.columns] # reverse all strings
desired_order = sorted(desired_order) # order them by 1_
desired_order = [x[::-1] for x in desired_order] # reverse them back

df_pivoted[desired_order]

相关问题