合并具有非唯一索引的多个数据帧

时间:2014-06-06 20:11:42

标签: python pandas

我有一堆熊猫时间序列。下面是一个示例(实际数据在每个系列中有大约100万个条目):

>>> for s in series:
    print s.head()
    print
2014-01-01 01:00:00   -0.546404
2014-01-01 01:00:00   -0.791217
2014-01-01 01:00:01    0.117944
2014-01-01 01:00:01   -1.033161
2014-01-01 01:00:02    0.013415
2014-01-01 01:00:02    0.368853
2014-01-01 01:00:02    0.380515
2014-01-01 01:00:02    0.976505
2014-01-01 01:00:02    0.881654
dtype: float64

2014-01-01 01:00:00   -0.111314
2014-01-01 01:00:01    0.792093
2014-01-01 01:00:01   -1.367650
2014-01-01 01:00:02   -0.469194
2014-01-01 01:00:02    0.569606
2014-01-01 01:00:02   -1.777805
dtype: float64

2014-01-01 01:00:00   -0.108123
2014-01-01 01:00:00   -1.518526
2014-01-01 01:00:00   -1.395465
2014-01-01 01:00:01    0.045677
2014-01-01 01:00:01    1.614789
2014-01-01 01:00:01    1.141460
2014-01-01 01:00:02    1.365290
dtype: float64

每个系列中的时间并不是唯一的。例如,最后一个系列在2014-01-01 01:00:00处有3个值。第二个系列当时只有一个值。 此外,并非所有时间都必须出现在所有系列中

我的目标是创建一个合并的DataFrame,其次数是各个时间序列中所有时间的联合。每个时间戳应根据需要重复多次。因此,如果上述系列中的时间戳发生(2, 0, 3, 4)次,则时间戳应在结果DataFrame中重复4次(最大频率)。每列的值应该"填充前进"。

例如,合并上述内容的结果应为:

                             c0                c1              c2
2014-01-01 01:00:00   -0.546404         -0.111314       -0.108123
2014-01-01 01:00:00   -0.791217         -0.111314       -1.518526
2014-01-01 01:00:00   -0.791217         -0.111314       -1.395465
2014-01-01 01:00:01    0.117944          0.792093        0.045677
2014-01-01 01:00:01   -1.033161         -1.367650        1.614789
2014-01-01 01:00:01   -1.033161         -1.367650        1.141460
2014-01-01 01:00:02    0.013415         -0.469194        1.365290
2014-01-01 01:00:02    0.368853          0.569606        1.365290
2014-01-01 01:00:02    0.380515         -1.777805        1.365290
2014-01-01 01:00:02    0.976505         -1.777805        1.365290
2014-01-01 01:00:02    0.881654         -1.777805        1.365290

了解尺寸和"唯一性"在我的真实数据中:

>>> [len(s.index.unique()) for s in series]
[48617, 48635, 48720, 48620]
>>> len(times)
51043
>>> [len(s) for s in series]
[1143409, 1143758, 1233646, 1242864]

以下是我的尝试:

我可以创建所有独特时间的联合:

uniques = [s.index.unique() for s in series]
times = uniques[0].union_many(uniques[1:])

我现在可以使用times索引每个系列:

series[0].loc[times]

但这似乎重复times中每个项目的值,这不是我想要的。

我无法使用reindex()times系列,因为每个系列的索引都不是唯一的。

我可以通过一个缓慢的Python循环来完成它,或者在Cython中完成它,但是有一个" pandas-only"如何做我想做的事情?

我使用以下代码创建了我的示例系列:

def make_series(n=3, rep=(0,5)):
    times = pandas.date_range('2014/01/01 01:00:00', periods=n, freq='S')
    reps = [random.randint(*rep) for _ in xrange(n)]
    dates = []
    values = numpy.random.randn(numpy.sum(reps))
    for date, rep in zip(times, reps):
        dates.extend([date]*rep)
    return pandas.Series(data=values, index=dates)

series = [make_series() for _ in xrange(3)]

2 个答案:

答案 0 :(得分:3)

非常几乎是一个结论:

In [11]: s0 = pd.Series([1, 2, 3], name='s0')

In [12]: s1 = pd.Series([1, 4, 5], name='s1')

In [13]: pd.concat([s0, s1], axis=1)
Out[13]:
   s0  s1
0   1   1
1   2   4
2   3   5

然而,concat无法处理重复的索引(它们应该如何合并,并且在你的情况下你不想以“普通”方式合并它们 - 作为组合)..

我认为你将使用groupby:

In [21]: s0 = pd.Series([1, 2, 3], [0, 0, 1], name='s0')

In [22]: s1 = pd.Series([1, 4, 5], [0, 1, 1], name='s1')

注意:我添加了一个更快的方法,适用于类似int的dtypes(如datetime64)。

我们希望为每个项目添加cumcounts的MultiIndex级别,这样我们就可以让索引变得独一无二:

In [23]: s0.groupby(level=0).cumcount()
Out[23]:
0    0
0    1
1    0
dtype: int64

注意:我似乎无法在没有DataFrame的情况下将列附加到索引中。

In [24]: df0 = pd.DataFrame(s0).set_index(s0.groupby(level=0).cumcount(), append=True)

In [25]: df1 = pd.DataFrame(s1).set_index(s1.groupby(level=0).cumcount(), append=True)

In [26]: df0
Out[26]:
     s0
0 0   1
  1   2
1 0   3

现在我们可以继续这些:

In [27]: res = pd.concat([df0, df1], axis=1)

In [28]: res
Out[28]:
     s0  s1
0 0   1   1
  1   2 NaN
1 0   3   4
  1 NaN   5

如果你想放弃cumcount级别:

In [29]: res.index = res.index.droplevel(1)

In [30]: res
Out[30]:
   s0  s1
0   1   1
0   2 NaN
1   3   4
1 NaN   5

现在你可以填写以获得所需的结果......(如果你担心向前填充不同的日期时间,你可以通过索引和ffill进行分组)。


如果每组中的重复上限是合理的(我选择1000,但更高的仍然是“合理的”!),你可以使用Float64Index如下(当然看起来更优雅):

s0.index = s0.index + (s0.groupby(level=0)._cumcount_array() / 1000.)
s1.index = s1.index + (s1.groupby(level=0)._cumcount_array() / 1000.)
res = pd.concat([s0, s1], axis=1)
res.index = res.index.values.astype('int64')

注意:我在这里使用私有方法,将cumcount作为numpy数组返回...
注2:这是pandas 0.14,在0.13中你必须将一个numpy数组传递给_cumcount_array,例如np.arange(len(s0))),0.13之前你运气不好 - 没有暨记录。

答案 1 :(得分:1)

这个怎么样 - 首先转换为带有标签列的数据帧,然后转换为concat()。

s1 = pd.Series(index=['4/4/14','4/4/14','4/5/14'],
                      data=[12.2,0.0,12.2])
s2 = pd.Series(index=['4/5/14','4/8/14'],
                      data=[14.2,3.0])
d1 = pd.DataFrame(a,columns=['a'])
d2 = pd.DataFrame(b,columns=['b'])

final_df = pd.merge(d1, d2, left_index=True, right_index=True, how='outer')

这给了我

           a     b
4/4/14  12.2   NaN
4/4/14   0.0   NaN
4/5/14  12.2   14.2
4/8/14   NaN   3.0
相关问题