【问题标题】:Storing and reading multiple histograms in a csv file在 csv 文件中存储和读取多个直方图
【发布时间】:2020-11-15 04:49:13
【问题描述】:

我正在处理以熊猫系列形式呈现的直方图,并表示观察集中随机变量的实现。我正在寻找一种有效的方式来存储和读取它们。

直方图的 bin 是 Series 的索引。例如:

histogram1 :
(-1.3747106810983318, 3.529160051186781]    0.012520
(3.529160051186781, 8.433030783471894]      0.013830
(8.433030783471894, 13.336901515757006]     0.016495
(13.336901515757006, 18.24077224804212]     0.007194
(18.24077224804212, 23.144642980327234]     0.041667
(23.144642980327234, 28.048513712612344]    0.000000

我想将其中几个直方图存储在一个 csv 文件中(每组随机变量一个文件,一个文件将存储约 100 个直方图),并在稍后完全按照存储前的方式读取它们(每个直方图从文件中作为单个系列,所有值作为浮点数)。

我该怎么做?既然速度很重要,有没有比 csv 文件更有效的方法?

因此,当一个变量的新实现出现时,我会从相应的文件中检索它的直方图并评估它“落入”的 bin。像这样:

# Not very elegant
for bin in histogram1.index:
    if 1.0232545 in bin:
        print("It's in!")
        print(histogram1.loc[bin])

谢谢!

【问题讨论】:

    标签: python pandas csv histogram


    【解决方案1】:

    您在这里讨论两个不同的主题:

    1. 存储多个系列的有效方法是什么?
    2. 如何从已形成的 IntervalIndex 中确定 float 的 bin?

    第一部分很简单。我会使用pandas.concat() 在保存到 csv 之前创建一个大框架(或者更确切地说

    pd.concat(histograms, keys=hist_names, names=['hist_name','bin']).rename('random_variable').to_frame().to_parquet()
    

    查看.to_parquet()this answerthis benchmark了解更多信息

    然后在回读时,选择单个直方图

    hist1 = df.loc[('hist1', :), 'random_variable']
    

    grouped = df.reset_index('hist_name').groupby('hist_name')
    hist1 = grouped.get_group('hist1')
    

    第二部分已经回答here。 简而言之,您需要通过以下方式展平 IntervalIndex:

    bins = hist1.index.right
    

    然后您可以使用 numpy.digitize 找到您的值(或值列表)的 bin:

    i = np.digitize(my_value, bins)
    return_value = hist1.iloc[i]
    

    编辑

    刚刚找到this answer 关于Indexing with an IntervalIndex,这也可以:

    return_value = hist1.loc[my_value]
    

    【讨论】:

    • 感谢您提供有据可查的答案!不幸的是,我无法使第一部分 (concat) 工作。我得到的最接近的方法是在重置索引后将直方图存储在字典中:dict = {'histo1':hist1.reset_index(), 'histo2':hist2.reset_index()} 并在字典上使用 concat:pd.concat(dict, ignore_index=True).set_index('index')。这给我留下了一个数据框,但没有个人名称:我无法使用您的解决方案单独读取它们。我也不能在上面使用to_parquet(),因为parquet must have string column names。你知道为什么吗?
    • 第二部分return_value = hist1.loc[my_value],是一个优雅的单行,谢谢!
    • 您需要使用concatkeysnames 参数,因此连接的df 中的索引将有两个级别(hist_name 和interval)...还要注意rename 之后concat,这应该将列名从 0 更改为 str
    • 我一开始就是这样做的,但它给了我一个错误:categories must match existing categories when appending
    猜你喜欢
    • 1970-01-01
    • 2017-09-08
    • 2019-03-22
    • 2022-01-08
    • 2018-06-15
    • 2022-01-19
    • 2018-07-26
    • 2016-10-30
    相关资源
    最近更新 更多