我有一个具有以下格式的数据框架:
我想将其"融合"成以下格式:
我该如何操作?
输入为数据框:
时间戳 | ID | Col1 | Col2 | Col3 | Col4 | 有用的列 |
---|---|---|---|---|---|---|
16/11/2021 | 1 | 0.2 | 0.1 | Col3 | ||
17/11/2021 | 1 | 0.3 | 0.8 | Col3 | ||
17/11/2021 | 2 | 10 | Col2 | |||
17/11/2021 | 3 | 0.1 | 2 | Col4 |
时间戳 | ID | 列名 | 值 |
---|---|---|---|
16/11/2021 | 1 | Col3 | 0.1 |
17/11/2021 | 1 | Col3 | 0.8 |
17/11/2021 | 2 | Col2 | 10 |
17/11/2021 | 3 | Col4 | 2 |
输入为数据框:
from numpy import nan
df = pd.DataFrame({'timestamp': ['16/11/2021', '17/11/2021', '17/11/2021', '17/11/2021'],
'ID': [1, 1, 2, 3],
'Col1': [0.2, 0.3, nan, nan],
'Col2': [nan, nan, 10.0, nan],
'Col3': [0.1, 0.8, nan, 0.1],
'Col4': [nan, nan, nan, 2.0],
'UsefulCol': ['Col3', 'Col3', 'Col2', 'Col4']})