【问题标题】:skip lines in a text file跳过文本文件中的行
【发布时间】:2018-09-10 00:23:33
【问题描述】:

我是 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)

【问题讨论】:

  • 请正确格式化您的代码。
  • 我想也许你应该打电话给party_list()party_list 也不返回任何东西

标签: python python-3.x pandas


【解决方案1】:

您可以通过构造函数的 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

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

【讨论】:

  • 谢谢你的工作。现在我有一个包含数据的 csv 文件和一个包含我需要从两者读取信息的数据的 txt 文件。特别是我需要 csv 中“Annual”列的总数和 txt 文件中的“Party”。我很困惑如何在 Python 中使用 pandas 来做到这一点。
  • 如果您发现有帮助的答案,请随时接受。如果您还有其他问题,可以将其作为另一个问题发布
猜你喜欢
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 2016-10-04
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多