1

I have the following data as part of a Pandas DataFrame, df::

  qsoName,filterID,aperMag 
0 PSOJ000,3,+19.284586
1 PSOJ007,2,+20.334393
2 PSOJ007,3,+20.226970
3 PSOJ007,4,+20.288778   
4 PSOJ007,5,+20.189209
5 PSOJ011,2,+21.037594
6 PSOJ011,4,+20.642813            
7 PSOJ011,5,+20.760576 

and I'd like to pick out the different values of df['aperMag'] for the one value of df['qsoName'], with -999.99999 being a default, e.g.

 PSOJ000,-999.99999,+19.284586,-999.99999,-999.99999
 PSOJ007,+20.334393,+20.226970,+20.288778,+20.189209
 PSOJ011,+21.037594,-999.99999,+20.642813,+20.760576 

This feels like df["qsoName"].duplicated() should work, but the reformatting of the DataFrame is the other key part.

4

1 回答 1

3

DataFrame.pivot与 一起使用DataFrame.fillna

df = df.pivot('qsoName','filterID','aperMag').fillna(-999.99999)

set_index使用unstackand 参数fill_value

df = df.set_index(['qsoName','filterID'])['aperMag'].unstack(fill_value=-999.99999)

print (df)
filterID           2           3           4           5
qsoName                                                 
PSOJ000  -999.999990   19.284586 -999.999990 -999.999990
PSOJ007    20.334393   20.226970   20.288778   20.189209
PSOJ011    21.037594 -999.999990   20.642813   20.760576

必要时最后:

df = df.reset_index().rename_axis(None,axis=1)
print (df)
   qsoName           2           3           4           5
0  PSOJ000 -999.999990   19.284586 -999.999990 -999.999990
1  PSOJ007   20.334393   20.226970   20.288778   20.189209
2  PSOJ011   21.037594 -999.999990   20.642813   20.760576

编辑:

问题是一些数据对 ( qsoName, filterID) 是重复的,所以需要pivot_table

df = df.pivot_table(index='qsoName',
                    columns='filterID', 
                    values='aperMag', 
                    fill_value=-999.99999, 
                    aggfunc='mean')
于 2019-02-05T14:25:18.023 回答