2015-01-10 2 views
1

나는 csv 샘플 파일을 읽고 .h5 데이터베이스에 저장하고 있습니다.pandas - DataFrame의 선택된 열만을 HDF5에 저장하는 방법

import pandas as pd 

df = pd.read_csv(filename + '.csv', sep=';') 

df.to_hdf('test.h5','key1',format='table',data_columns=['User_ID','Year']) 

다음 .h5 열을 불과 몇에 전달 선택

User_ID;Longitude;Latitude;Year;Month;String 
267261661;-3.86580025;40.32170825;2013;12;hello world 
171255468;-3.83879575;40.05035005;2013;12;hello world 
343588169;-3.70759531;40.4055946;2014;2;hello world 
908779052;-3.8356385;40.1249459;2013;8;hello world 
289540518;-3.6723114;40.3801642;2013;11;hello world 
635876313;-3.8323166;40.3379393;2012;10;hello world 
175160914;-3.53687933;40.35101274;2013;12;hello world 
155029860;-3.68555076;40.47688417;2013;11;hello world 

나는 팬더 to_hdf와 .h5 저장소에 넣어했습니다 다음과 같이 .CSV가 구성되어 나는 특히, HDFStore 및 read_hdf를 사용하여 .h5 파일에 저장된 열에서 다른 결과를 얻을 것 : 나는 '년'열을 데이터베이스에 저장 (단지 'USER_ID'등을 기대하는 것입니다

store = pd.HDFStore('test.h5') 
>>> store 
>>> <class 'pandas.io.pytables.HDFStore'> 
File path: /test.h5 
/key1   frame_table (typ->appendable,nrows->8,ncols->6,indexers->[index],dc->[User_ID,Year]) 

), 물론 ncols-> 6은 실제로 모든 열이 .h5 파일에 저장되었음을 의미합니다.

내가 pd.read_hdf 사용하여 파일 읽기 시도 할 경우 :

hdf = pd.read_hdf('test.h5','key1') 

을하고 키를 묻는 :

나는 원래의 모든 열 때문에 기대하고있어되지 않습니다
hdf.keys() 
>>> Index([u'User_ID', u'Longitude', u'Latitude', u'Year', u'Month', u'String'], dtype='object') 

. csv 파일은 여전히 ​​.h5 데이터베이스에 있습니다. 데이터베이스의 크기를 줄이기 위해 .h5에 열을 선택하여 저장하는 방법은 무엇입니까?

도움 주셔서 감사합니다.

답변

10

파일에 쓸 때 열을 선택하기 만하면됩니다.

cols_to_keep = ['User_ID', 'Year'] 
df[cols_to_keep].to_hdf(...) 
+0

좋아요! 참으로 쉬운 일이었습니다 ... read_hdf의 "data_columns"는 .h5 파일을 나중에 읽을 수있는 열을 선택할 수 있다는 것을 나타냅니다. –

+0

나는 hdf5 파일에 대해 아무것도 모른다. 너는 그걸로 너 혼자 야. (@fblamanna) –

+0

@fblamanna는 data_columns의 목적과 정확히 일치합니다 (http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns). – Jeff

관련 문제