我有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_位置
使用globals()[newName]=redShiftKey,这样就可以了
您可以使用字典,其中每个键都包含一个数据帧作为值:
要动态创建变量,您需要检查以下讨论:generating variable names on fly in python
但是,字典策略更好,因为您可以处理动态的
^{pr2}$n
数量的csv文件,而且您可以轻松地遍历它们:相关问题 更多 >
编程相关推荐