gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:25:13 24 4
gpt4 key购买 nike

我在文件夹中有 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

最佳答案

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

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

关于python - 使用函数导入 CSV 文件并重命名数据框名称 - python 3.6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45688816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com