【问题标题】:Combining parameter and value while reading in csv files在读取 csv 文件时结合参数和值
【发布时间】:2018-08-24 18:19:59
【问题描述】:

如果我有这样的文档,列名在第 1 行和第 2 行中重复,参数的单位在第 3 行中,我如何调用 pd.read_csv 以便它创建一个带有标题的数据框列名和单位以及值?

Time    Speed   Torque
time    speed   torque 
seconds m/s Nm 
1   4000    229,5
2   4000    228,7
3   4000    230,1

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

    如果想要MultiIndex 在列中使用参数header=[0,1] 来转换第一行和第二行而不跳过行:

    import pandas as pd
    
    temp=u"""Time    Speed   Torque
    time    speed   torque 
    seconds m/s Nm 
    1   4000    229,5
    2   4000    228,7
    3   4000    230,1"""
    #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
    df = pd.read_csv(pd.compat.StringIO(temp), sep="\s+", header=[0,1], skiprows=[0])
    print (df)
         time speed torque
      seconds   m/s     Nm
    0       1  4000  229,5
    1       2  4000  228,7
    2       3  4000  230,1
    
    print (df.columns)
    MultiIndex(levels=[['speed', 'time', 'torque'], ['Nm', 'm/s', 'seconds']],
               labels=[[1, 0, 2], [2, 1, 0]])
    

    import pandas as pd
    
    temp=u"""Time    Speed   Torque
    time    speed   torque 
    seconds m/s Nm 
    1   4000    229,5
    2   4000    228,7
    3   4000    230,1"""
    #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
    df = pd.read_csv(pd.compat.StringIO(temp), sep="\s+", header=[0,1], skiprows=[1])
    print (df)
         Time Speed Torque
      seconds   m/s     Nm
    0       1  4000  229,5
    1       2  4000  228,7
    2       3  4000  230,1
    

    如果想省略第二行和第三行,只使用skiprows参数:

    import pandas as pd
    
    temp=u"""Time    Speed   Torque
    time    speed   torque 
    seconds m/s Nm 
    1   4000    229,5
    2   4000    228,7
    3   4000    230,1"""
    #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
    df = pd.read_csv(pd.compat.StringIO(temp), sep="\s+", skiprows=[1, 2])
    print (df)
       Time  Speed Torque
    0     1   4000  229,5
    1     2   4000  228,7
    2     3   4000  230,1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2023-03-17
      • 2013-07-05
      • 2019-09-09
      • 2016-02-11
      相关资源
      最近更新 更多