2017-05-21 16 views
0

파일을 가져 와서 정보를 파이썬으로 데이터 프레임에 넣으려면이 프로세스를 20 번 반복해야합니다. 아래 코드를 모두 실행 시키면 더 빨리이 작업을 수행 할 수 있습니다.파일 가져 오기 및 데이터 프레임 넣기 (프로세스 최적화)

df = pandas.DataFrame() 
file20 = os.path.abspath('Fasting/times/20time.csv') 
time20 = pandas.read_csv(file20, index_col=0, header=0) 
df['time20'] = time20['Gen1'] + '_'+ time20['Gen2'] 
file19 = os.path.abspath('Fasting/times/19time.csv') 
time19 = pandas.read_csv(file19, index_col=0, header=0) 
df['time19'] = time19['Gen1'] + '_'+ time19['Gen2'] 
file18 = os.path.abspath('Fasting/times/18time.csv') 
time18 = pandas.read_csv(file18, index_col=0, header=0) 
df['time18'] = time18['Gen1'] + '_'+ time18['Gen2'] 
file17 = os.path.abspath('Fasting/times/17time.csv') 
time17 = pandas.read_csv(file17, index_col=0, header=0) 
.... 

*** 안녕하세요! 내가 나중에 time17 = pandas.read_csv(file17, index_col=0, header=0)에서 그들과 함께 일해야하기 때문에 나는 혼자 구원 받기 위해 매번 필요하다는 것을 깨달았다. 루프에서 데이터 프레임과 데이터 프레임을 동시에 수행 할 수 있습니까? 고마워요! 그것이 내가 필요가 거의 것입니다, 대단히 감사합니다,

files = [str(i) + 'time' for i in reversed(range(1, 21))] 
pieces = [] 
    # much faster to start with empty list than empty DataFrame 

for file in files: 
    path = 'Fasting/times/%s.csv' % file 
    frame = pd.read_csv(path, index_col=0, header=0) 
    pieces.append(frame['Gen1'] + '_' + frame['Gen2']) 

df = pd.concat(pieces, axis=1) # may need ignore_index=True 
df.columns = files 

답변

1

이 사용 해보세요. 그러나 새로운 데이터 프레임에서는 파일`df [ 'timei'] = timei [ 'Gen1'] + '_'+ timei [ 'Gen2']`와 같은 많은 열만 원합니다. 이렇게하면 filei의 모든 열과 새 열 (time1 [ 'Gen1'] + '_'+ timei [ 'Gen2'])이 추가됩니다. 고맙습니다!!
+0

안녕 : – Mee

+0

나는 당신이 의미하는 것을 본다 - 나의 응답을 업데이트하고, 그것을 시험해 보아라. 파일 당 열이 하나만 추가됩니다. 명심하십시오. 이것은 파일 열이 문자열이라고 가정합니다. 안전을 위해'df [ 'Gen1'] .stype (str) + '_'+ df [ 'Gen2'] .stat (str)'을 사용할 수 있습니다. –