【问题标题】:pandas read_csv() skiprows=[0] giving issues? [duplicate]pandas read_csv() skiprows=[0] 给出问题? [复制]
【发布时间】:2020-02-02 10:17:32
【问题描述】:

我正在尝试读取 pandas 中的 csv。我的文件开头如下:

 Site,Tank ID,Product,Volume,Temperature,Dip Time
   aaa,bbb,....
   .....

我是这样读的:

df = pd.DataFrame()
    date_col = ['Dip Time']
    data = pd.read_csv(atg_path, delimiter=',', skiprows=[1], skipinitialspace=True,
                                   dayfirst=True,
                                   parse_dates=date_col)

这里跳过第一行数据。但我需要它。

如果我使用skiprows=[0],则会在某些列上出现错误,例如ValueError: 'Dip Time' is not in list

我不知道为什么?它不应该跳过任何数据。怎么了?

【问题讨论】:

  • 您要跳过阅读标题,还是第一行数据 ("aaa,bbb,..." )?您实际上想通过skiprows=[0] 实现什么目标?您的问题不清楚。
  • skiprows = 0 (integer) 表示“不要跳过任何行”,所以没有效果。而skiprows = [0] (list with one element, 0) 表示“跳过第0行,即标题行”,因此它跳过标题(带有列名)并读取数据。
  • pandas.read_csv() doc 解释了skiprows 的作用,包括整数和列表

标签: python pandas csv


【解决方案1】:

我觉得这里的参数skiprows不是必须的,可以省略。

但如果传递 0 值则意味着 don't skip any rows:

skiprows=0

import pandas as pd
from io import StringIO

temp="""Site,Tank ID,Product,Volume,Temperature,Dip Time
aaa,bbb,ccc,ddd,eee,fff
a,b,c,d,e,f
"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp))
print (df)
  Site Tank ID Product Volume Temperature Dip Time
0  aaa     bbb     ccc    ddd         eee      fff
1    a       b       c      d           e        f

temp="""Site,Tank ID,Product,Volume,Temperature,Dip Time
aaa,bbb,ccc,ddd,eee,fff
a,b,c,d,e,f
"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), skiprows=0)
print (df)
  Site Tank ID Product Volume Temperature Dip Time
0  aaa     bbb     ccc    ddd         eee      fff
1    a       b       c      d           e        f

但是如果通过[0]表示删除文件的第一行,这里的header表示"skip the 0'th row, i.e. the headed row

temp="""Site,Tank ID,Product,Volume,Temperature,Dip Time
aaa,bbb,ccc,ddd,eee,fff
a,b,c,d,e,f
"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), skiprows=[0])
print (df)
  aaa bbb ccc ddd eee fff
0   a   b   c   d   e   f

【讨论】:

  • 谢谢我跳过该参数现在可以正常工作。你能多解释一下为什么 skiprows[0] 给我一个问题以及为什么使用该参数吗?
  • 这不是答案。 skiprows = 0(整数)表示“不要跳过任何行”,所以没有效果。而skiprows = [0] (list with one element, 0) 表示“跳过第0行,即标题行”,所以它跳过标题(带有列名)并读取数据。
  • @smci - 对不起,你是对的。没有写清楚,答案已编辑。谢谢。
猜你喜欢
  • 2019-01-02
  • 1970-01-01
  • 2015-02-17
  • 2016-10-02
  • 2016-12-13
  • 2020-02-22
  • 2017-07-16
  • 2020-04-03
  • 1970-01-01
相关资源
最近更新 更多