Python 迭代地将单个组中的数据帧附加到h5文件
我有一个小脚本,用于从用户输入目录读取csv文件,并将其转换为单个HDF5文件:Python 迭代地将单个组中的数据帧附加到h5文件,python,pandas,hdf5,hdfstore,Python,Pandas,Hdf5,Hdfstore,我有一个小脚本,用于从用户输入目录读取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()
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中打开它,它看起来像这样:
另外,如果我使用另一个目录再次运行脚本,它将继续向根组追加新组(每个文件一个)
我希望每次运行脚本时,它都将文件组附加到根目录中的新组(subject)中。大概是这样的:
我觉得这可能与我传入store.append
的密钥有关,因为现在它使用文件名作为密钥。我能够手动传递键并附加所需的数据帧,但这不是我想要的最终目标
一些建议将是伟大的!多谢各位
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']>
导入h5py
#加载文件
f=h5py.File('test.h5','r')
打印(f['sample'].keys())
打印(f['sample1'].keys())
f、 关闭()
非常感谢,这正是我想要的!你能澄清一下
f'{group}/{k}
中f
的功能是什么吗?很高兴我能帮上忙。澄清一下,f
不是一个函数:它是一个函数。它用于格式化字符串文字。它取代了python 3.6中的str.format()。它类似于使用r
来表示原始字符串:r'some\string\with\forward\slashes'
本质上,它使用大括号{}
格式化带有预定义变量的字符串