【问题标题】:import all csv files in directory as pandas dfs and name them as csv filenames将目录中的所有 csv 文件导入为 pandas dfs 并将它们命名为 csv 文件名
【发布时间】:2016-10-15 10:53:54
【问题描述】:

我正在尝试编写一个脚本,它将目录中的所有 .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

任何帮助表示赞赏,谢谢。

【问题讨论】:

  • 如何将您的 DF 保存为 DF 的字典,其中的键可以按照您的意愿命名?
  • 我认为@MaxU 的解决方案是最好的,因为它允许您在不显式定义变量的情况下指定变量名称
  • 感谢@MaxU,我确实希望每个 dfs 都可以直接访问,但现在将按照建议使用字典。

标签: python csv pandas


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 2012-12-31
    • 1970-01-01
    • 2016-12-17
    • 2020-03-28
    • 1970-01-01
    • 2013-08-21
    • 2014-07-05
    相关资源
    最近更新 更多