【问题标题】:Skip file if value is not in data using python如果值不在使用 python 的数据中,则跳过文件
【发布时间】:2022-08-18 23:11:43
【问题描述】:

使用我当前的代码,如果 csv 文件在我正在寻找的实际数据中不包含值,我将尝试跳过它。

基本上,如果它有 \"PROD_NAME\" 作为列,那么它会查找该字符串并将其替换为该语句中的第二个字符串,但我文件夹中的第一个文件没有此列名,因此脚本失败。我已经研究过跳过的方法,但只看到了基于文件名本身的跳过方法,而不是文件中没有正确信息的数据。任何帮助,将不胜感激。谢谢!

def worker(files):
    filenames = glob.glob(dest_dir + \'\\\\*.csv\')
    for filename in filenames:
            
        my_file = Path(os.path.join(dest_dir, filename))
        
        #read header
        with open(filename) as f:
            read_data = f.read()
        header = read_data[:read_data.find(\'!1\')]
        idx = header.find(\'\\n\')
        

        # read data
        df1 = pd.read_csv(filename, skiprows=1, encoding=\'ISO-8859-1\', nrows=1) # read column header only - to get the list of columns
        dtypes = {}
        for col in df1.columns:# make all columns text, to avoid formatting errors
            dtypes[col] = \'str\'
        df1 = pd.read_csv(filename, dtype=dtypes, skiprows=1, encoding=\'ISO-8859-1\', quotechar=\"\'\", delimiter=\'\\t\')
        
        
        df1.loc[df1[\'PROD_NAME\'].str.contains(\'NA_NRF\'), \'PROD_NAME\'] = \'FA_GUAR\'
        file_count += 1 # count the fil
            
worker(files)
  • 您可以尝试使用旧的 try... except... 语句。

标签: python pandas dataframe csv


【解决方案1】:

您可以在转换之前添加一个 if 语句吗

if 'PROD_NAME' in df1.columns:            
    df1.loc[df1['PROD_NAME'].str.contains('NA_NRF'), 'PROD_NAME'] = 'FA_GUAR'
    
file_count += 1 # count the fil

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 2020-06-24
    • 1970-01-01
    • 2017-02-15
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多