python稀疏序列数据结构
我正在迭代处理一些数据,如下所示:python稀疏序列数据结构,python,pandas,scipy,Python,Pandas,Scipy,我正在迭代处理一些数据,如下所示: 进行一些处理并生成相应的结果 ~~~~时间戳1 a 0.3 b 0.2 c 0.4 做一些进一步的处理,结果应该是 ~~~~时间戳1时间戳2 a 0.3 b 0.2 0.3 c 0.4 d 0.1 做一些进一步的处理,结果应该是 ~~~~时间戳1时间戳2时间戳3 a 0.30.1 b 0.2 0.3 c 0.4 d 0.1 e 0.5 f 0.2 g 0.6 这意味着,每一步都会添加一个新列。行也可能增长。关键是,在每一列中,只有一部分数据具有值。
~~~~时间戳1
a 0.3
b 0.2
c 0.4
~~~~时间戳1时间戳2
a 0.3
b 0.2 0.3
c 0.4
d 0.1
~~~~时间戳1时间戳2时间戳3
a 0.30.1
b 0.2 0.3
c 0.4
d 0.1
e 0.5
f 0.2
g 0.6
在每个时间步,将生成一个新序列,例如[('b',0.3),('d',0.1)]。我的目标是将它们存储在一个统一的数据结构中,如SparseSerie。您可以使用索引作为键来创建和合并连续的SparseAframe
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
我们可以确认这是一个sparaframe
>>> 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
>>df.info()
索引:6个条目,a至f
数据列(共4列):
时间戳1 1非空浮点64
时间戳2 2非空浮点64
时间戳3 3非空浮点64
时间戳4 3非空浮点64
数据类型:float64(4)
内存使用:240.0+字节
希望这有帮助。生成新序列的规则是什么?在每个时间步都会生成一个新序列,例如[('b',0.3),('d',0.1)]。是的,但是如何选择这些随机数和字母?第三种情况是稀疏序列还是3?你已经阅读了SparseSeries(和SparseDataFrame)文档和示例了吗?>但是你如何挑选那些随机数字和字母呢?它们是数据处理的结果。每一步都有文档流。因此,我们事先不知道字母是什么(它也可以是一个单词或短语)