亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

以迭代方式將單個組中的熊貓數據幀追加到 h5 文件

以迭代方式將單個組中的熊貓數據幀追加到 h5 文件

小唯快跑啊 2022-09-27 09:42:28
我有一個小腳本,旨在從用戶輸入目錄中讀取csv文件并將其轉換為單個HDF5文件:path = input('Insert the directory path:')file_list = []for file in glob.glob(path):    file_list.append(file)for filename in file_list:    df = pd.read_csv(filename)    key = Path(filename).resolve().stem    with pd.HDFStore('test.h5') as store:        store.append(key=key, value=df, format='table', data_columns=df.columns)當前正在執行的操作是將每個文件(以數據幀格式)作為一個組進行追加。如果我在 vitables 中打開它,它看起來像這樣:此外,如果我使用另一個目錄再次運行腳本,它將繼續將新組(每個文件一個)附加到根組。我想要的是每次運行腳本時,它都會將文件組附加到根目錄的新組(主題)中。像這樣:我覺得這可能與傳入的密鑰有關,因為現在它使用文件名作為密鑰。我能夠手動傳遞密鑰并附加所需的數據幀,但這不是我想要的終點。store.append一些建議會很棒!謝謝
查看完整描述

1 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

import glob

import os

import pandas as pd


# inputs

path = input('Insert the directory path:')

group = input('Insert a group name: ')


# create a list of file paths

file_list = [file for file in glob.glob(path)]

# dict comprehension to create keys from file name and values from the csv files

dfs = {os.path.basename(os.path.normpath(filename)).split('.')[0]: pd.read_csv(filename) for filename in file_list}


# loop though the dataframes

for k,df in dfs.items():

    # store the HDF5 file

    store = pd.HDFStore('test.h5')

    # append df to a group and assign the key with f-strings

    store.append(f'{group}/{k}', df, format='table', data_columns=df.columns)

    # close the file

    store.close()

我為該組運行了上述代碼兩次,該組的結果如下:samplesample1


import h5py

# load file

f = h5py.File('test.h5', 'r')

print(f['sample'].keys())

print(f['sample1'].keys())

f.close()


<KeysViewHDF5 ['untitled', 'untitled1']>

<KeysViewHDF5 ['untitled2', 'untitled3']>

http://img1.sycdn.imooc.com//633255340001045f02970269.jpg

查看完整回答
反對 回復 2022-09-27
  • 1 回答
  • 0 關注
  • 81 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號