【问题标题】:Deleting Rows (Data Wrangling) in Python with csv and/or pandas modules使用 csv 和/或 pandas 模块在 Python 中删除行(数据整理)
【发布时间】:2018-08-10 23:34:33
【问题描述】:

我有一组 csv 文件,我正试图在将它们放入数据库之前对其进行清理。这些文件用制表符划定,有两种格式。一种格式如下所示:

Some text string

Field1\tField2\tField3\tField4

Some text string 总是以相同的顺序开始,所以我想用它来识别需要修改的文件。从那里我可以删除前两行(第一行和接下来的空行)。

我已经能够成功地找到以这个字符串开头的文件,但我只能通过遍历每一行来做到这一点,这不是我想要做的最好的方法。

其中 csvFiles 是目录中 csv 文件的列表:

在 csv 模块中:

for csvFile in csvFiles:
    with open(csvFile, newline='') as f:
        for line in f:
            if line.startswith("Some"):
                print("Found it")

在熊猫中:

for csvFile in csvFiles:
    standings = pandas.read_csv(csvFile, sep='/t', header=None, engine='python')
        for row in standings:
            if standings[row][0].startswith("Some"):
                print("Found it")

我想简单地选择第一行并用 if 语句检查它,最好是在 pandas 中,但我没有成功。 pandas 将第一行解释为标题,并为每个后续行分配行索引,因此我无法按索引选择第一行。我已尝试设置header=None 以便为每一行编制索引,但仍无法按索引选择第一行。

我试图弄清楚如何遍历 csvFiles 列表中的文件,找到以 Some text string 开头的文件,然后仅从这些文件中删除前两行以及后面的一些行。

我理想的解决方案是这样开始的:

for csvFile in csvFiles:
    standings = pandas.read_csv(csvFile, sep='/t', header=None, engine='python')
        if standings[row][0].startswith("Some"):
            print("Found it")
            #do some stuff

【问题讨论】:

    标签: python python-3.x pandas csv


    【解决方案1】:

    由于您只是匹配一行文本,因此为此使用 Pandas 没有任何好处(实际上它可能会更慢且更困难)。但是如果你小心的话,你可以打开每个文件一次:

    for csvFile in csvFiles:
        with open(csvFile) as f:
            line = f.readline()
            if line.startswith("Some"):
                f.readline() # skip one more line (validate it if you like)
                df = pd.read_csv(f, sep='\t', header=None)
                # now  you have the data you want
    

    我们的想法是将打开的文件句柄传递给read_csv(),并在您使用了它不需要的“元数据”后让它继续读取。

    您可能还希望将列名和/或类型指定为 read_csv(),以便您的 DataFrame 以您想要的方式显示,而无需进一步操作。提前指定 dtypes 可以加快大文件的解析速度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 2017-11-05
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多