在Pandas导入CSV时,跳过行

2024-03-28 14:36:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pandas.read_csv()导入一个.csv文件,但是我不想导入数据文件的第二行(索引为0的索引为1的行)。

我看不出如何不导入它,因为与命令一起使用的参数似乎不明确:

从熊猫网站:

skiprows : list-like or integer

Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file."

如果我将skiprows=1放入参数中,它如何知道是跳过第一行还是跳过索引为1的行?


Tags: or文件ofcsvtheto命令pandas
3条回答

你可以试试自己:

>>> import pandas as pd
>>> from StringIO import StringIO
>>> s = """1, 2
... 3, 4
... 5, 6"""
>>> pd.read_csv(StringIO(s), skiprows=[1], header=None)
   0  1
0  1  2
1  5  6
>>> pd.read_csv(StringIO(s), skiprows=1, header=None)
   0  1
0  3  4
1  5  6

我还没有名声可以评论,但我想添加到alko答案中以供进一步参考。

docs

skiprows: A collection of numbers for rows in the file to skip. Can also be an integer to skip the first n rows

我在读取csv文件时运行skiprows时遇到了同样的问题。 我在做skip_rows=1这不起作用

简单的例子给出了一个如何在读取csv文件时使用skiprows的想法。

import pandas as pd

#skiprows=1 will skip first line and try to read from second line
df = pandas.read_csv('my_csv_file.csv', skiprows=1)

#print the data frame
df

相关问题 更多 >