以同样的方式转换CSV文件的文件夹,然后用python输出多个数据帧

Transform a folder of CSV files the same way, then output multiple dataframes with python

我有一个需要转换和 manipulate/clean 的 csv 文件文件夹,输出一个数据框,然后我可以继续使用它。我想要一个数据框,每个 CSV 文件都有一个唯一的标题。我编写的代码能够按照我想要的方式操作一个 csv 文件,最后有一个干净的数据框,但是我在尝试遍历文件夹并转换所有文件时被绊倒了csv 文件,每个 csv 以一个数据框结尾。

这是我一直在使用的代码:

import pandas as pd
import numpy as np
import os
from os import listdir
import glob
import win32com.client

filepath = 'C:/Users/me/BMI'

xl = win32com.client.gencache.EnsureDispatch('Excel.Application')

for f in glob.glob(filepath+'/*.xls'):
    fullname = os.path.abspath(f)
    xl.Workbooks.Open(fullname)
    xl.ActiveWorkbook.SaveAs(Filename=fullname.replace('.xls','.csv'),
        FileFormat=win32com.client.constants.xlCSVMSDOS,
        CreateBackup=False)
    xl.ActiveWorkbook.Close(SaveChanges=False)

os.listdir('C:/Users/me/BMI')

def find_csv_filenames( path_to_dir, suffix=".csv" ):
    filenames = listdir(path_to_dir)
    return [ filename for filename in filenames if filename.endswith( suffix ) ]

filenames = list(find_csv_filenames(filepath))

for i in filenaames:
   df = pd.read_csv(filepath+'/'+i)
   del df['Unnamed: 0']

# Extract by rows - create list of rows that are blank
nul_rows = list(df[df.isnull().all(axis=1)].index)

list_of_dataframes = []
list_of_dataframes.append(df.iloc[:nul_rows[0] - 1,:])
for i in range(len(nul_rows) - 1):
    list_of_dataframes.append(df.iloc[nul_rows[i]+1:nul_rows[i],:])

list_of_dataframes.append(df.iloc[nul_rows[4] - 1::])

# Remove null columns
cleaned_tables = []
for _df in list_of_dataframes:
    cleaned_tables.append(_df.dropna(axis=1, how='all'))

# cleaned_tables is a list of the dataframes
print(cleaned_tables[0])

# drop second row of data frame (subtitle)
df = df.drop(df.index[0])

#set up headers in row 1
df=df.set_value(1, df.columns[0], 'brands')

# change column names to proper headers (brand as first column, years of data following)
for i in list(range(len(df.columns))):
    df = df.rename(columns={df.columns[i]: df.iloc[0][df.columns[i]]})

#get rid of double headers (row 1)
df = df.drop(df.index[0])

如果您有转换单个 .csv 的代码,并且您希望对目录中的所有 .csv 执行相同的操作,并最终为每个 .csv 生成一个唯一的 DataFrame,您可以这样做吗?

import pandas as pd
import numpy as np
import os

filepath = r'C:\Users\me\BMI'

df_list = []
for file in os.listdir():
  if file.endswith('.csv'):
    temp_df = pd.read_csv(os.path.join(filepath, file), encoding='utf-8')
    # transformation and clean-up steps here...

    # ...
    df_list.append(temp_df)

每个 temp_df 将存储在 df_list 中。

你可以像这样在最后将它们连接成一个最终的 DataFrame:

one_df = pd.concat(df_list, ignore_index=True)

如果您 运行 遇到将文件读入数据帧的问题,请尝试定义分隔符 sep(如果您的数据不是逗号分隔)和 encoding 如果您的 csv 文件以特定的编码进行编码。例如:

pd.read_csv(..., sep='\t', encoding='cp1252')