【问题标题】:Python-Replacing scores with actual value(Transposing)Python-用实际值替换分数(转置)
【发布时间】:2018-07-23 03:29:59
【问题描述】:

我的数据看起来像

 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 中使用)的东西,但不确定如何使用它们。

【问题讨论】:

    标签: python transpose


    【解决方案1】:

    使用上面的数据

    import pandas as pd
    from io import StringIO
    import itertools
    
    text = u'Time \t          Pressure\tNormal/Abnormal\n11/30/2011 22:50\t74.3\t  0\n11/30/2011 23:00\t74.8\t  1\n11/30/2011 23:10\t77.7\t  1\n11/30/2011 23:30\t74.8\t  0\n11/30/2011 13:00\t80.9\t  0'
    
    df = pd.read_table(StringIO(text))
    normal = df.loc[df['Normal/Abnormal'] == 0].as_matrix()
    abnormal = df.loc[df['Normal/Abnormal'] == 1].as_matrix()
    
    columns = ["Time", "Normal", "Time", "Abnormal"]
    out = []
    
    for nr, ar in itertools.izip_longest(normal, abnormal, fillvalue=['', '']):
        # Concat rows horizontally (i.e. hstack)
        r = list(nr[:2]) + list(ar[:2])
        out.append(r)
    
    df2 = pd.DataFrame(out, columns=columns)
    
    print df2.to_string(index=False)
    
    ''' 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
    '''
    

    【讨论】:

      【解决方案2】:

      构造两个数据框,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
      

      【讨论】:

      • 谢谢!在实际数据中,我的分数为 1 和 0。我需要创建 2 列,然后在这些列中填充压力值。得分为 1 的将在异常列中具有相对于时间的压力值。希望我现在把问题说清楚。
      • 对不起,我觉得你的评论让我更困惑了。
      • 有什么建议吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2012-11-23
      相关资源
      最近更新 更多