1

我有一个 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])
4

1 回答 1

1

如果您有转换单个 .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')
于 2017-06-16T17:10:31.317 回答