【问题标题】:How to skip text being used as column heading using python如何使用python跳过用作列标题的文本
【发布时间】:2016-04-08 04:29:10
【问题描述】:

我正在使用 Pandas 在 Python 中导入 Web 日志文本文件。 Python 正在读取标题,但是使用文本“字段:”作为标题,然后在末尾添加了另一列空白(NaN)。如何停止将此文本用作列标题?

这是我的代码:

arr = pd.read_table("path", skiprows=3, delim_whitespace=True,      na_values=True)

这是文件的开头:

软件:Microsoft Internet Information Services 7.5

版本:1.0

日期:2014-08-01 00:00:25

字段:日期时间

2014-08-01 00:00:25...

结果是“字段”被用作列标题,并且正在为“时间”列创建一个充满 NaN 值的列。

【问题讨论】:

    标签: python pandas text import columnheader


    【解决方案1】:

    您可以调用read_table 两次。

    # reads the forth line into 1x1 df being a string, 
    # then splits it and skips the first field:
    col_names = pd.read_table('path', skiprows=3, nrows=1, header=None).iloc[0,0].split()[1:]
    # reads the actual data:
    df = pd.read_table('path', sep=' ', skiprows=4, names=col_names)
    

    如果您已经知道列的名称(例如datetime),那就更简单了:

    df = pd.read_table('path', sep=' ', skiprows=4, names = ['date', 'time'])
    

    【讨论】:

      【解决方案2】:

      我想你可能想要skiprows = 4header = None

      【讨论】:

      • 谢谢,我这样做是一种解决方法,并在使用此 qanda 时添加了列标题:stackoverflow.com/questions/17018638/… 但肯定有更好的方法,而不是让它读取错误的文本
      • 哦,是的,我不明白你的问题。您应该只编辑文件并将'Fields: ' 替换为''(您可以在python 脚本中使用replace 执行此操作)
      猜你喜欢
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2011-11-27
      相关资源
      最近更新 更多