![](/img/trans.png)
[英]How to import all csv files in one folder and make the filename the variable name in pandas?
[英]import all csv files in directory as pandas dfs and name them as csv filenames
我正在嘗試編寫一個腳本,將目錄中的所有.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.