首页 > 解决方案 > Python-用实际值替换分数(转置)

问题描述

我有这个看起来像的数据

 Time 	          Pressure	Normal/Abnormal
11/30/2011 22:50	74.3	  0
11/30/2011 23:00	74.8	  1
11/30/2011 23:10	77.7	  1
11/30/2011 23:30	74.8	  0
11/30/2011 13:00	80.9	  0

Desired Output:

Time 	           Normal	Time 	           Abnormal
11/30/2011 22:50	74.3	11/30/2011 23:00	74.8
11/30/2011 23:30	74.8	11/30/2011 23:10	77.7
11/30/2011 13:00	80.9		


我想转置“所需输出”中提到的行。我知道我需要使用类似于 melt 和 cast(在 R 中使用)的东西,但不确定如何使用它们。

标签: pythontranspose

解决方案


构造两个数据框,1个正常,1个异常,然后连接和编辑列名

out = pd.concat([
  df[df['Normal/Abnormal'] == k].iloc[:, [0,1]].reset_index(drop=True)
  for k in [0, 1]], axis=1
)
out.columns = ['Time', 'Normal', 'Time', 'Abnormal']
out
               Time  Normal              Time  Abnormal
0  11/30/2011 22:50    74.3  11/30/2011 23:00      74.8
1  11/30/2011 23:30    74.8  11/30/2011 23:10      77.7
2  11/30/2011 13:00    80.9               NaN       NaN

推荐阅读