跳过文本文件中的行

时间:2018-03-31 01:09:29

标签: python python-3.x pandas

我是Python的新手,我们正在使用pandas来读取文本文件并从特定行检索数据。

我的文本文件中列出了44行,但我只需要35-44行。我需要排除一切,但总统","办公室","左办公室","党"。我有这个功能,但它没有读取我的df1,这将是我的数据帧。

def party_list():
    df1 = pd.read_table("presidents.txt", delimiter=",",usecols=["President ", "Took office ","Left office ", "Party "])
    location1=r' /users/Paula/PycharmProjects/Spring 2018_Paula/ '
f = open("presidents.txt",'r')
while True:
    line = f.readline()
    if line == "":
        break
    print(line)

1 个答案:

答案 0 :(得分:0)

您可以通过构造函数的skiprows参数省略前N行:

df1 = pd.read_table(
    "presidents.txt",
    delimiter=',',
    usecols=["President ", "Took office ","Left office ", "Party "],
    skiprows=34
)

您还可以阅读整个数据框,然后通过.tail(10)获取最后N行:

df1 = pd.read_table("presidents.txt", delimiter=",",usecols=["President ", "Took office ","Left office ", "Party "])
df1 = df1.tail(10)  ## 10 is actually the default amount

还有其他几种方法可以做到这一点:)