【问题标题】:Iteratively append pandas dataframes in a single group to h5 file将单个组中的 pandas 数据帧迭代地附加到 h5 文件
【发布时间】:2020-07-15 23:41:18
【问题描述】:

我有一个小脚本,用于从用户输入目录读取 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 的键有关,因为现在它使用文件名作为键。我能够手动传递密钥并附加所需的数据帧,但这不是我想要的最终目标。

一些建议会很棒!谢谢

【问题讨论】:

    标签: python pandas hdf5 hdfstore


    【解决方案1】:
    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()
    

    我为sample 组和sample1 组运行了两次上述代码,结果如下:

    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']>
    

    【讨论】:

    • 非常感谢,这正是我想要的!你能澄清一下ff'{group}/{k}'中的作用是什么吗?
    • 很高兴我能帮上忙。澄清一下,f 不是一个函数:它是一个f-string。它用于格式化字符串文字。它在 python 3.6 中替换了str.format()。它类似于使用r 来表示原始字符串:r'some\string\with\forward\slashes' 本质上,它使用花括号{} 格式化具有预定义变量的字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2015-12-21
    • 2019-11-30
    • 2023-04-10
    • 2021-05-08
    • 2018-03-20
    • 2020-02-02
    相关资源
    最近更新 更多