简体   繁体   English

Pandas - 根据哪一列不为空在新列中填充值

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

I have a dataframe like this:我有一个像这样的 dataframe:

a一个 b b c c d d
1 1 0.325 0.325
2 2 0.23378 0.23378
3 3 2.3242 2.3242
4 4 0.42 0.42
5 5 6.293 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. a、b、c、d四列中只有一个非NA值。 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.我想将这些值聚合成一个列value (或水温)和值的“位置”,即新column (或水深)列中的关联列名。

Expected output format:预期的 output 格式:

value价值 column柱子
1 1 0.325 0.325 b b
2 2 0.23378 0.23378 c c
3 3 2.3242 2.3242 b b
4 4 0.42 0.42 a一个
5 5 6.293 6.293 a一个

Use DataFrame.stack with DataFrame.rename_axis :使用DataFrame.stackDataFrame.rename_axis

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM