簡體   English   中英

有沒有更簡單的方法從多個 CSV 文件中過濾出行並將它們粘貼到新的 csv 文件中? 我在使用 for 循環時遇到問題

[英]Is there an easier way to filter out rows from multiple CSV files and paste them into a new csv file? IM having issues doing that using a for loop

#Purpose: to read CSV files from every every csv files in the directory. Filter the rows with the column that say 'fail" from the csv file. Then copy and paste those rows onto a new CSV file. 


# import necessary libraries
from sqlite3 import Row
import pandas as pd
import os
import glob
import csv

# Writing to a CSV
# using Python
import csv


# the path to your csv file directory.
mycsvdir = 'C:\Users\'' #this is where all the csv files will be housed.

# use glob to get all the csv files
# get all the csv files in that directory (assuming they have the extension .csv)
csvfiles = glob.glob(os.path.join(mycsvdir, '*.csv'))
   

# loop through the files and read them in with pandas
dataframes = []  # a list to hold all the individual pandas DataFrames
for csvfile in csv_files:
    
    # read the csv file
    df = pd.read_csv(csvfile)
    dataframes.append(df)

    #print(row['roi_id'], row['result']) #roi_id is the column label for the first cell on the csv, result is the Jth column label
dataframes = dataframes[dataframes['result'].str.contains('fail')]
    # print out to a new csv file
dataframes.to_csv('ROI_Fail.csv') #rewrite this to mirror the variable you want to save the failed rows in.


        

我嘗試運行此腳本,但遇到了一些錯誤。 首先,我知道我的縮進是關閉的(這里是新手),我在 for 循環下遇到一個大錯誤,說“csv_files”未定義。 任何幫助將不勝感激。

這里有兩個問題:

第一個有點簡單 - for 循環中的變量應該是 csvfiles,而不是 csv_files。

第二個(修復上面的問題時會顯示)是您將數據幀列表視為數據幀。

腳本中的對象“dataframes”是一個列表,您要將從 CSV 文件創建的數據幀附加到該列表。 因此,您不能像您嘗試的那樣按列名對它們進行索引。

如果您的數據框具有相同的布局,我建議您使用 df.concat 將所有數據框連接成一個,然后像您在此處所做的那樣過濾行。

full_dataframe = pd.concat(dataframes, axis=0)
full_dataframe = full_dataframe[full_dataframe['result'].str.contains('fail')]

作為進一步發布的提示,我建議您還發布程序的完整回溯。 它可以幫助我們准確了解您在執行代碼時遇到的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM