简体   繁体   中英

Reshaping a pandas data frame on multiple columns

I have data frame that looks like this:

questions = ['What color?', 'What day?', 'How cold?', 'What color?', 'What color?']
category = ['Something1', 'Something2', 'Something1', 'Something2', 'something3']
answers = ['red', 'tuesday', '45', 'blue', 'red']
ids = [0, 1, 2, 3, 0]
df = pd.DataFrame({'id': [0, 1, 2, 0, 0], 'questions': questions, 'answers': 
answers})

>>> id questions    answers category
    0  What color? red      Something1
    1  What day?   tuesday  Something2
    2  How cold?   45       Something1
    0 What color?  blue     Something2
    0 What color?  red      Something3

I am trying to reshape by category, id, and question to get to this:

    How cold?|Something1    What color?|Something1  What color?|Something2   what color?|Something3   What day?|Something2
id          
0         None                   red                     Blue                       red                   None
1         None                   None                    None                       None                  tuesday
2         45                     None                    None                       None                  None

I have tried similar ideas from this former question: pandas: how to run a pivot with a multi-index? , but no luck so far.

Are you looking for something like this:

df['questions'] = df.questions + '/' +  df.category

df1 = pd.pivot_table(df, values='answers', index='id',columns='questions', aggfunc='first')

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM