具有稀疏序列的Python数据结构

标签 python pandas scipy

我正在迭代处理一些数据,如下所示:

  1. 进行一些处理并生成结果 ~~~时间戳1 0.3 0.2 约0.4

  2. 做一些进一步的处理,结果应该是 ~~~时间戳1 时间戳2 0.3 0.2 0.3 约0.4 直径0.1

  3. 做一些进一步的处理,结果应该是 ~~~时间戳1 时间戳2 时间戳3 0.3 0.1 0.2 0.3 约0.4 直径0.1 0.5 0.2 克0.6

这意味着,每一步都会添加一个新列。该行也可能会增长。关键是,在每一列中只有一部分数据具有值。其他的则不然,因此 SparseSeries 似乎是适合此目的的数据结构。

===问题===

问题是,如何连续生成这样一个SparseSeries?

谢谢!

注意:

在每个时间步都会生成一个新的序列,例如[('b', 0.3), ('d', 0.1)]。我的目标是将它们存储在统一的数据结构中,例如 SparseSerie。

最佳答案

您可以使用索引作为键来创建和合并连续的 SparseDataFrame。

import pandas as pd

# suppose you have successive inputs like below
# I put some differently-sized lists for demonstration purpose
ps = [[('a', 0.1)], 
      [('b', 0.2), ('c', 0.3)], 
      [('d', 0.4), ('e', 0.5), ('f', 0.8)], 
      [('a', 0.7), ('b', 0.8), ('c', 0.9)]]

df = pd.DataFrame().to_sparse()

# Suppose you will have some 'timestamp' value from somewhere
# This loop is just for demonstration purpose
for i, p in enumerate(ps):
    df1 = (pd.DataFrame(p, columns=['entry', 'timestamp{}'.format(i+1)])
           .set_index('entry')
           .to_sparse()
           )
    df = pd.merge(df, df1, left_index=True, right_index=True, how='outer')

现在df看起来像这样

>>> df
       timestamp1  timestamp2  timestamp3  timestamp4
entry                                                
a             0.1         NaN         NaN         0.7
b             NaN         0.2         NaN         0.8
c             NaN         0.3         NaN         0.9
d             NaN         NaN         0.4         NaN
e             NaN         NaN         0.5         NaN
f             NaN         NaN         0.8         NaN

我们可以确认这是一个SparseDataFrame

>>> df.info()
<class 'pandas.core.sparse.frame.SparseDataFrame'>
Index: 6 entries, a to f
Data columns (total 4 columns):
timestamp1    1 non-null float64
timestamp2    2 non-null float64
timestamp3    3 non-null float64
timestamp4    3 non-null float64
dtypes: float64(4)
memory usage: 240.0+ bytes

希望这有帮助。

关于具有稀疏序列的Python数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51803649/

相关文章:

Python 和 Pandas - 按日期排序

python - 为数组 A 中的唯一值获取数组 B 中的 NumPy 数组索引,对于两个数组中存在的值,与数组 A 对齐

python - 有没有办法连接 "list display"中的 2 个模型字段名称以在 Django Admin 中显示为一列?

python - 在 Tkinter 中使用 askdirectory() 选择文件夹时显示所有文件

python - 在 Python 中标记数据(将数据转换为模式)

c++ - 结合python和c++,或者cython,优化一个函数;最大似然示例;对c++的了解很少

python - 为什么 X.dot(X.T) 在 numpy 中需要这么多内存?

python - 插入新元素作为链表的头部 Python

python - Pandas group by on groupby 到列表列表

python - 使用 Pandas 从 CSV 导入空列