使用函数导入CSV文件,并将数据帧重命名为python 3.6

2024-10-04 05:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2/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_指示器和redShiftKey_位置


Tags: 文件csv数据inimportosasprod
2条回答

使用globals()[newName]=redShiftKey,这样就可以了

您可以使用字典,其中每个键都包含一个数据帧作为值:

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文件,而且您可以轻松地遍历它们:

^{pr2}$

相关问题 更多 >