【问题标题】:Pivoting a Pandas Dataframe containing strings - add the columns in the first time one only and other wise it add values in any column旋转包含字符串的 Pandas 数据框 - 仅在第一次添加列,否则在任何列中添加值
【发布时间】:2019-11-17 08:35:52
【问题描述】:

大家早上好 我有许多具有以下格式但在 measure 列中具有不同值的文件

subject_id     hour    measure      value

2               1      heart rate    40
4               3      SPO2          high

我想使用数据透视表重塑数据,所以我使用以下代码

    df1 = df.pivot_table(index=["subject_id" ,"hour"], columns='measure', values=['value'], aggfunc='first')
    df1.columns = df1.columns.droplevel()
    df1 = df1.reset_index()
    df1.columns=df1.columns.tolist()
    print (df1)
 with open('patients.csv', 'a',newline='') as f: 
    df1.to_csv(f, header=True)

效果很好,给我以下文件

subject_id    hour    heart rate    spo2
2              1        40          
4              3                    high

但是当我想将另一个文件连接到同一个文件时出现问题patients.csv 假设新文件是

subject_id     hour        measure      value

    5               4      resp          50
    6               4      urine         200

我使用上面提到的相同代码来添加值和新列

 df1 = df.pivot_table(index=["subject_id" ,"hour"], columns='measure', values=['value'], aggfunc='first')
        df1.columns = df1.columns.droplevel()
        df1 = df1.reset_index()
        df1.columns=df1.columns.tolist()
        print (df1)
     with open('patients.csv', 'a',newline='') as f: 
        df1.to_csv(f, header=True)

因此它没有将新度量添加为新列,它只添加新患者并将值添加到旧列中,如下所示

subject_id         hour    heart rate       spo2
    2              1        40          
    4              3                        high
    5              4        50
    6              4                        200

所以输出文件不正确,我希望它如下

 subject_id         hour    heart rate       spo2     resp    urine
    2              1        40          
    4              3                        high        
    5              4                                   50
    6              4                                            200

我该如何解决这个问题 任何帮助将不胜感激

【问题讨论】:

  • 如何将第二个文件连接到第一个文件?请在问题中添加代码,而不是作为评论。
  • ok,完成,你可以检查了
  • 我认为您只是错误地复制了以前的代码...(修复后我将删除此评论)
  • 它是相同的代码,但它与每个文件一起运行以在第一次将结果连接到最终文件我们只能使用 save **pivot_table.to_csv('\\ path) **

标签: python python-3.x pandas python-2.7


【解决方案1】:

您需要对python 中的数据进行操作,而不是每次都将其添加到文件中。一旦你从“patients.csv”中的第一个文件中获得数据,阅读它:

original_data = pd.read_csv("patients.csv")

在您像在代码中那样创建df1 之后,将它们与:

full_data = pd.concat([original_data, df1], sort=False)

然后你可以保存它:

full_data.to_csv("patients.csv", index=False) # Always better option to work with csv files than "with open... as..."

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多