将目录中的所有csv文件作为pandas dfs导入,并将它们命名为csv文件名

use*_*ser 5 python csv pandas

我正在尝试编写一个脚本,将目录中的所有.csv文件作为数据帧导入我的工作区.每个数据帧应命名为csv文件(减去扩展名:.csv).

这是我到目前为止所做的,但很难理解如何为循环中的数据帧分配正确的名称.我已经看过建议使用的帖子,exec()但这似乎不是一个很好的解决方案.

path = "../3_Data/Benefits"                     # dir path
all_files = glob.glob(os.path.join(path, "*.csv")) #make list of paths

for file in all_files:
    dfn = file.split('\\')[-1].split('.')[0] # create string for df name
    dfn = pd.read_csv(file,skiprows=5) # This line should assign to the value stored in dfn
Run Code Online (Sandbox Code Playgroud)

任何帮助表示感谢,谢谢.

Rom*_*ain 6

DataFrame没有name他们的索引可以拥有name.这是如何设置它.

import glob
import os

path = "./data/"
all_files = glob.glob(os.path.join(path, "*.csv")) #make list of paths

for file in all_files:
    # Getting the file name without extension
    file_name = os.path.splitext(os.path.basename(file))[0]
    # Reading the file content to create a DataFrame
    dfn = pd.read_csv(file)
    # Setting the file name (without extension) as the index name
    dfn.index.name = file_name

# Example showing the Name in the print output

#      FirstYear  LastYear
# Name                     
# 0         1990      2007
# 1         2001      2001
# 2         2001      2008
Run Code Online (Sandbox Code Playgroud)