Python 如何获得傻瓜和群比

Python 如何获得傻瓜和群比,python,pandas,dataframe,group-by,pivot-table,Python,Pandas,Dataframe,Group By,Pivot Table,我有下面的数据框 Q A A a h A b i A c j B d k B a l B b m C c n 我想要dummy和groupby a b c d e f g A h i j nan nan nan nan B l nan nan nan k nan nan C nan nan n nan nan nan nan col=df.Q 我必须申请get\u du

我有下面的数据框

   Q  A
A  a  h  
A  b  i
A  c  j
B  d  k
B  a  l 
B  b  m
C  c  n
我想要dummy和groupby

    a   b   c   d    e   f   g
A   h   i   j  nan  nan nan nan
B   l  nan nan nan  k   nan nan      
C  nan nan  n  nan  nan nan nan
col=df.Q

我必须申请
get\u dummies
groupby
,但我想不出来

如何获得此结果?

您似乎需要:

如有必要,然后:

编辑:

如果数据中存在重复项,则最好使用
groupby
join

print (df)
   Q  A
A  a  h
A  b  i
A  c  j
B  d  k
B  a  l
B  b  m <-duplicates B b
B  b  t <-duplicates B b
C  c  n


df = df.reset_index().groupby(['index','Q'])['A'].apply(','.join).unstack()
print (df)
Q         a     b     c     d
index                        
A         h     i     j  None
B         l   m,t  None     k
C      None  None     n  None
cols = list('abcdefg')
print (df.reindex_axis(cols, axis=1).replace({None:np.nan}))
Q        a    b    c    d   e   f   g
index                                
A        h    i    j  NaN NaN NaN NaN
B        l    m  NaN    k NaN NaN NaN
C      NaN  NaN    n  NaN NaN NaN NaN
print (df)
   Q  A
A  a  h
A  b  i
A  c  j
B  d  k
B  a  l
B  b  m <-duplicates B b
B  b  t <-duplicates B b
C  c  n


df = df.reset_index().groupby(['index','Q'])['A'].apply(','.join).unstack()
print (df)
Q         a     b     c     d
index                        
A         h     i     j  None
B         l   m,t  None     k
C      None  None     n  None
#aggfunc='first' - get only first value, another values are lost
df1 = df.reset_index().pivot_table(index='index', columns='Q', values='A', aggfunc='first')
print (df1)
Q         a     b     c     d
index                        
A         h     i     j  None
B         l     m  None     k
C      None  None     n  None
Q         a     b     c     d

#aggfunc='sum' - summed data, no separator
df2 = df.reset_index().pivot_table(index='index', columns='Q', values='A', aggfunc='sum')
print (df2)
index                        
A         h     i     j  None
B         l    mt  None     k
C      None  None     n  None
Q         a     b     c     d

#aggfunc=','.join - summed data with separator
df3 = df.reset_index().pivot_table(index='index', columns='Q', values='A', aggfunc=','.join)
print (df3)
index                        
A         h     i     j  None
B         l   m,t  None     k
C      None  None     n  None