使用函数导入CSV文件并重命名数据框名称 - python 3.6

时间:2017-08-15 08:07:17

标签: python python-3.x pandas

我在文件夹中有2个/更多csv文件,我想将这些文件导入到不同的数据框,并希望按文件名重命名数据框。

import os
import pandas as pd

redShiftKeyFolderPath = r'D:\Sunil_Work\temp8\Prod_IMFIFSS2017' # contains 2 csv files i.e Prod_IMFIFSS2017_Indicator.csv & Prod_IMFIFSS2017_Location.csv

def importRedshiftKeys(redShiftKeyFolderPath):
    for file in os.listdir(redShiftKeyFolderPath):
        if file.endswith('.csv'):
            redShiftKey = pd.read_csv(os.path.join(redShiftKeyFolderPath, file), dtype = object) # importing

            i = file.rfind('_'); file = file[i:]; rDfName = 'redShiftKey_' + file.replace('_', '').replace('.csv', '') # taking last part of the file name after _ & excluding .csv
            print('Need to rename dataframe as: ', rDfName)

            # Here i want to rename dataframe: "redShiftKey" with new name stored in "rDfName"
    return

importRedshiftKeys(redShiftKeyFolderPath)

我期待2个数据帧,即redShiftKey_Indicator& redShiftKey_Location

2 个答案:

答案 0 :(得分:3)

您可以使用字典,其中每个键都将数据帧保存为值:

import os
import pandas as pd

redShiftKeyFolderPath = r'D:\Sunil_Work\temp8\Prod_IMFIFSS2017' # contains 2 csv files i.e Prod_IMFIFSS2017_Indicator.csv & Prod_IMFIFSS2017_Location.csv

def importRedshiftKeys(redShiftKeyFolderPath):
    data = {}
    for file in os.listdir(redShiftKeyFolderPath):
        if file.endswith('.csv'):
            csv_file_name = file 

            i = file.rfind('_'); file = file[i:]; rDfName = 'redShiftKey_' + file.replace('_', '').replace('.csv', '') # taking last part of the file name after _ & excluding .csv
            data[rDfName] = redShiftKey = pd.read_csv(os.path.join(redShiftKeyFolderPath, csv_file_name), dtype = object) # importing

    return data

importRedshiftKeys(redShiftKeyFolderPath)

要动态创建变量,您需要查看此讨论:generating variable names on fly in python

但是,字典策略更好,因为您可以处理动态n个csv文件,而且您可以轻松地遍历它们:

for Df_name, df in data.items():
    # do any further processing in here 

答案 1 :(得分:1)

使用globals()[newName] = redShiftKey,这将起作用