我正在迭代处理一些数据,如下所示:
进行一些处理并生成结果
~~~时间戳1 0.3 0.2 约0.4
做一些进一步的处理,结果应该是
~~~时间戳1 时间戳2 0.3 0.2 0.3 约0.4 直径0.1
做一些进一步的处理,结果应该是
~~~时间戳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/