简体   繁体   中英

How to properly stack or unstack pandas dataframe?

I've been trying to stack or unstack the following dataframe:

       Eelde  Southend-On-Sea     Ulceby        date
   24.000000              NaN        NaN  2020-02-16
1  22.673913              NaN        NaN  2020-02-17
0        NaN              NaN  24.312500  2020-02-17
0        NaN        19.130435        NaN  2020-02-17
0  14.000000              NaN        NaN  2020-02-17
1  19.239130              NaN        NaN  2020-02-18
0        NaN              NaN  19.687500  2020-02-18
0        NaN        17.760870        NaN  2020-02-18
0  20.500000              NaN        NaN  2020-02-18
1  12.978261              NaN        NaN  2020-02-19
0        NaN              NaN  19.041667  2020-02-19
0        NaN        14.200000        NaN  2020-02-19

Let us not focus on the double index, but focusing on combining the rows.

The desired output should look like:

   index     Eelde  Southend-On-Sea      Ulceby     date
0         24.000000             NaN         NaN     2020-02-16
0      0  14.00000        19.130435     24.312500   2020-02-17
1      1  19.23913        17.76087      19.6875     2020-02-18
2      0  12.978261       14.200000     19.041667   2020-02-19

如果想要每组每列的第一个非缺失值(如果存在),请使用GroupBy.first

df1 = df.groupby('date', as_index=False).first()

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