我正在尝试编写一个脚本,将目录中的所有 .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
任何帮助表示赞赏,谢谢。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)