python - 如何将大量数据附加到 Pandas HDFStore 并获得自然的唯一索引?

标签 python indexing pandas dataframe hdfstore

我正在将大量 http 日志 (80GB+) 导入 Pandas HDFStore 进行统计处理。即使在单个导入文件中,我也需要在加载内容时对其进行批处理。到目前为止,我的策略是将解析的行读入 DataFrame,然后将 DataFrame 存储到 HDFStore。我的目标是让索引键对于 DataStore 中的单个键是唯一的,但每个 DataFrame 都会重新启动它自己的索引值。我原以为 HDFStore.append() 会有某种机制告诉它忽略 DataFrame 索引值并继续添加到我的 HDFStore 键的现有索引值但似乎无法找到它。如何在让 HDFStore 增加其现有索引值的同时导入 DataFrames 并忽略其中包含的索引值?下面的示例代码每 10 行批处理一次。实物自然要大一些。

if hd_file_name:
        """
        HDF5 output file specified.
        """

        hdf_output = pd.HDFStore(hd_file_name, complib='blosc')
        print hdf_output

        columns = ['source', 'ip', 'unknown', 'user', 'timestamp', 'http_verb', 'path', 'protocol', 'http_result', 
                   'response_size', 'referrer', 'user_agent', 'response_time']

        source_name = str(log_file.name.rsplit('/')[-1])   # HDF5 Tables don't play nice with unicode so explicit str(). :(

        batch = []

        for count, line in enumerate(log_file,1):
            data = parse_line(line, rejected_output = reject_output)

            # Add our source file name to the beginning.
            data.insert(0, source_name )    
            batch.append(data)

            if not (count % 10):
                df = pd.DataFrame( batch, columns = columns )
                hdf_output.append(KEY_NAME, df)
                batch = []

        if (count % 10):
            df = pd.DataFrame( batch, columns = columns )
            hdf_output.append(KEY_NAME, df)

最佳答案

你可以这样做。唯一的诀窍是第一次存储表不存在,因此 get_storer 将引发。

import pandas as pd
import numpy as np
import os

files = ['test1.csv','test2.csv']
for f in files:
    pd.DataFrame(np.random.randn(10,2),columns=list('AB')).to_csv(f)

path = 'test.h5'
if os.path.exists(path):
    os.remove(path)

with pd.get_store(path) as store:
    for f in files:
        df = pd.read_csv(f,index_col=0)
        try:
            nrows = store.get_storer('foo').nrows
        except:
            nrows = 0

        df.index = pd.Series(df.index) + nrows
        store.append('foo',df)


In [10]: pd.read_hdf('test.h5','foo')
Out[10]: 
           A         B
0   0.772017  0.153381
1   0.304131  0.368573
2   0.995465  0.799655
3  -0.326959  0.923280
4  -0.808376  0.449645
5  -1.336166  0.236968
6  -0.593523 -0.359080
7  -0.098482  0.037183
8   0.315627 -1.027162
9  -1.084545 -1.922288
10  0.412407 -0.270916
11  1.835381 -0.737411
12 -0.607571  0.507790
13  0.043509 -0.294086
14 -0.465210  0.880798
15  1.181344  0.354411
16  0.501892 -0.358361
17  0.633256  0.419397
18  0.932354 -0.603932
19 -0.341135  2.453220

您实际上不一定需要全局唯一索引(除非您想要一个),因为 HDFStore(通过 PyTables)通过对行进行唯一编号来提供一个索引。您可以随时添加这些选择参数。

In [11]: pd.read_hdf('test.h5','foo',start=12,stop=15)
Out[11]: 
           A         B
12 -0.607571  0.507790
13  0.043509 -0.294086
14 -0.465210  0.880798

关于python - 如何将大量数据附加到 Pandas HDFStore 并获得自然的唯一索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16997048/

相关文章:

Python获取参数,例如字符串 'function(parameter)'

mysql - 使用子查询的查询需要比使用固定数据而不是子查询的相同查询更长的时间

python - 根据当前值更新 Pandas 数据帧值

python - 将负日期时间转换为 NaT

python - 如何用 Pandas 数据框中的列值替换单元格中的索引值

python - Pandas 中的 TextFileReader 参数

Python: 成功运行代码后,requests 没有 get 属性

python - 结合pygame和twisted

python - 如何使用 python 日志记录的 SMTPHandler 和 SSL 发送电子邮件

javascript - JS 将单个索引中的 2 个数组及其各个值合并到 1 个数组中的单个索引中