[英]Pandas - fill value in new column based on which column is not empty
I have a dataframe like this:我有一个像这样的 dataframe:
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.
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 ![]() |
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
:使用
DataFrame.stack
和DataFrame.rename_axis
:
df = df.stack().rename_axis(['value','column']).reset_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.