0

Consider the following dataframe:

data = {
  'A': [0, 0, 0, 1, 1, 1, 1],
  'B': list('ABCABCD'),
  'C': range(12, 19)
}
pd.DataFrame(data).set_index(['A', 'B'])

      C
A B    
0 A  12
  B  13
  C  14
1 A  15
  B  16
  C  17
  D  18

I need to convert this dataframe to

   0    1
A  12   15
B  13   16
C  14   17
D  NaN  18

Context: I am doing a groupby operation, and the apply function is return a series. groupby then converts that to a multi index, but it is easiest for me to represent my data with group labels as columns instead of rows.

oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
skgbanga
  • 2,477
  • 2
  • 20
  • 29

1 Answers1

0

You can try with pd.pivot_table():

import pandas as pd 
import matplotlib.pyplot as plt
data = {'A': [0, 0, 0, 1, 1, 1, 1],'B': list('ABCABCD'),'C': range(12, 19)}
df = pd.DataFrame(data).set_index(['A', 'B'])
print(df)
new_df = pd.pivot_table(df,columns=['A'],index=['B'],values=['C'])
print(new_df)

Output:

A     0     1
B
A  12.0  15.0
B  13.0  16.0
C  14.0  17.0
D   NaN  18.0
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53