简体   繁体   中英

Pandas - fill value in new column based on which column is not empty

I have a dataframe like this:

a b c d
1 0.325
2 0.23378
3 2.3242
4 0.42
5 6.293

The four columns represent different water depths and the values are temperature measurements. There is only one non-NA value in the four columns a, b, c, d. I want to aggregate the values into one column value (or water temperature) and the 'position' of the value, ie the associated column name in a new column (or water depth) column.

Expected output format:

value column
1 0.325 b
2 0.23378 c
3 2.3242 b
4 0.42 a
5 6.293 a

Use DataFrame.stack with DataFrame.rename_axis :

df = df.stack().rename_axis(['value','column']).reset_index()

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