2016-10-27 181 views
0

是否可以使用pandas.DataFrame複製此csv的結構?multiheader pandas dataframe

enter image description here

所有數據被從一個HDF5文件拉出,然後解析出的屬性到pd.DataFrame

我擔心是該meta headermeta data(線1和2在CSV )不符合attribute headerattribute data的長度或形狀。

這裏是我叫pd.DataFrame

# Meta Pandas DataFrame 
    meta_df = pd.DataFrame(index=range(0, 8760, 24), columns=['source', 'location_id', 'state', 'country', 'latitude', 
                   'longitude', 'time_zone', 'elevation', 'clearsky_dhi', 
                   'clearsky_dni', 'clearsky_ghi', 'dewpoint_unit', 
                   'temperature_unit']) 
    # Meta Header & Data 
    meta_df['source'] = source 
    meta_df['location_id'] = location_id 
    meta_df['state'] = state 
    meta_df['country'] = country 
    meta_df['latitude'] = latitude 
    meta_df['longitude'] = longitude 
    meta_df['time_zone'] = local_time 
    meta_df['elevation'] = elevation 
    meta_df['clearsky_dhi'] = clearsky_dhi 
    meta_df['clearsky_dni'] = clearsky_dni 
    meta_df['clearsky_ghi'] = clearsky_ghi 
    meta_df['dewpoint_unit'] = dewpoint_unit 
    meta_df['temperature_unit'] = temperature_unit 

    # Attribute Pandas DataFrame 
    att_df = pd.DataFrame(index=range(0, 8760, 24), columns=['dhi', 'dni', 'ghi', 'source', 'dew_point', 'temperature']) 

    # Attribute Header & Data 
    att_df['year'] = year 
    att_df['month'] = month 
    att_df['day'] = day 
    att_df['hour'] = hour 
    att_df['minute'] = minute 
    att_df['dhi'] = dhi 
    att_df['dni'] = dni 
    att_df['ghi'] = ghi 
    att_df['dew_point'] = dew_point 
    att_df['temperature'] = temperature 

    # Make one DataFrame with multiple headers? 
    # Do something, then export to csv. 
    df.to_csv(ndir_root + ndir + '/' + fname + '.csv', index=False) 

是它最好創建兩個單獨的dataframes,然後將它們堆疊垂直創建第三個數據幀並導出最終爲CSV?

bueller?

回答

1

我認爲你可以通過.to_csv()來做到這一點,因爲這個方法接受一個文件路徑(如你所做的)或緩衝區。我假設你知道元標題,元數據和屬性標題字符串的順序,所以你可以選擇如何將它們寫入文件。下面列出了您缺少的作品。

with open('output.csv','w') as fid: 
    # write your meta header etc., here assumed to be a list of strings 
    fid.write(','.join(meta_header) + '\n') 
    fid.write(','.join(meta_data) + '\n') 
    fid.write(','.join(attribute_header) + '\n') 

    # now write attr_df to a csv by passing data to your fid buffer 
    attr_df.to_csv(fid, sep=',', header=False, index=False)