2016-10-15 1 views
2

디렉토리의 모든 .csv 파일을 작업 영역의 데이터 프레임으로 가져 오는 스크립트를 작성하려고합니다. 각 데이터 프레임의 이름은 csv 파일로 지정해야합니다 (확장자 : .csv 제외).디렉토리의 모든 csv 파일을 pandas dfs로 가져 와서 파일 이름을 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 

감사합니다.

+2

DF를 원하는대로 이름을 붙일 수있는 DF 사전으로 저장하는 방법은 무엇입니까? – MaxU

+0

@ MaxU의 솔루션은 변수를 명시 적으로 정의하지 않고 변수 이름을 지정할 수있게 해준다고 생각합니다. –

+0

감사합니다. @MaxU, 각각의 dfs를 직접 액세스 할 수 있었지만 지금은 제안 된대로 사용할 것입니다. – user

답변

4

DataFramename이 아니며 인덱스는 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 
관련 문제