在python数据框中融化/旋转

问题描述

我正在尝试将输入数据帧转换为输出数据帧,但是代码无法正常工作,不确定我在哪里丢失了。

我尝试过的事情:

  • 我尝试使用pandas.pivot(index,column,values)函数,但是它 向我显示错误,不确定我在哪里失踪。我也试过玩 在上面的命令中与索引有关,但仍然有点正确 回答。我也尝试使用melt命令来到达输出数据帧 但这确实有用。

    Input.melt(id_vars ='MeasurementDate',var_name = ['UID'],value_name = ['Value'])

输入数据框:

Input=pd.DataFrame({'MeasurementDate':['22-07-2020','23-07-2020','24-07-2020','25-07-2020','26-07-2020','27-07-2020','28-07-2020'
],'U1':['V1.1','V1.2','V1.3','V1.4','V1.5','V1.6','V1.7'
],'U2':['V2.1','V2.2','V2.3','V2.4','V2.5','V2.6','V2.7'
],'Forecast_Generation_Date':[
'22-09-2020','23-09-2020','24-09-2020','25-09-2020','26-09-2020','27-09-2020','28-09-2020'

]} )


print(Input)

输出数据框:

Output=pd.DataFrame({'MeasurementDate':['22-07-2020','28-07-2020','22-07-2020','UID':['U1','U1','U2','U2'

],'Value':['V1.1','V1.7','V2.1','V2.7'],'Forecast_Generation_Date':['22-09-2020','28-09-2020','22-09-2020','28-09-2020'


]} )
print(Output)

解决方法

您没有传递df=pd.DataFrame({'MeasurementDate':['22-07-2020','23-07-2020','24-07-2020','25-07-2020','26-07-2020','27-07-2020','28-07-2020'],'U1':['V1.1','V1.2','V1.3','V1.4','V1.5','V1.6','V1.7'],'U2':['V2.1','V2.2','V2.3','V2.4','V2.5','V2.6','V2.7'],'Forecast_Generation_Date':['22-09-2020','23-09-2020','24-09-2020','25-09-2020','26-09-2020','27-09-2020','28-09-2020'] } ) df = df.melt(id_vars=['MeasurementDate','Forecast_Generation_Date'],value_vars=['U1','U2'],var_name='UID') df 参数。

+-------------------+----------------------------+-------+---------+
| MeasurementDate   | Forecast_Generation_Date   | UID   | value   |
+===================+============================+=======+=========+
| 22-07-2020        | 22-09-2020                 | U1    | V1.1    |
| 23-07-2020        | 23-09-2020                 | U1    | V1.2    |
| 24-07-2020        | 24-09-2020                 | U1    | V1.3    |
| 25-07-2020        | 25-09-2020                 | U1    | V1.4    |
| 26-07-2020        | 26-09-2020                 | U1    | V1.5    |
| 27-07-2020        | 27-09-2020                 | U1    | V1.6    |
| 28-07-2020        | 28-09-2020                 | U1    | V1.7    |
| 22-07-2020        | 22-09-2020                 | U2    | V2.1    |
| 23-07-2020        | 23-09-2020                 | U2    | V2.2    |
| 24-07-2020        | 24-09-2020                 | U2    | V2.3    |
| 25-07-2020        | 25-09-2020                 | U2    | V2.4    |
| 26-07-2020        | 26-09-2020                 | U2    | V2.5    |
| 27-07-2020        | 27-09-2020                 | U2    | V2.6    |
| 28-07-2020        | 28-09-2020                 | U2    | V2.7    |
+-------------------+----------------------------+-------+---------+

输出

Post