【发布时间】:2015-01-14 19:56:43
【问题描述】:
一般问题
我有一个pandas.DataFrame 的任意列表(让我们使用 2 来保持示例清晰),我想在 Index 上 concat 他们:
- 既不是
inner也不是现有DataFrames的outer连接 - 是一个不同的、独立的
Index,但仅在所有DataFrame中都有日期
例如,取以下 2 个DataFrame 的(注意Index 形状的区别):
In [01]: d1 = pandas.DataFrame( numpy.random.randn(15, 4),
columns = ['a', 'b', 'c', 'd'],
index = pandas.DatetimeIndex(start = '01/01/2001',
freq = 'b',
periods = 15)
)
In [02]: d2 = pandas.DataFrame( numpy.random.randn(17, 4),
columns = ['e', 'f', 'g', 'h'],
index = pandas.DatetimeIndex(start = '01/05/2001',
freq = 'b',
periods = 17)
)
我想将这两个DataFrame 加入到相交的Index 上,例如my_index,在这里构造:
In [03]: ind = range(0, 10, 2)
In [04]: my_index = d2.index[ind].copy()
所以下面的结果应该和下面的结果一样:
In [05]: d1.loc[my_index, :].join(d2.loc[my_index, :] )
Out[65]:
a b c d e f \
2001-01-05 1.702556 -0.885554 0.766257 -0.731700 -1.071232 1.806680
2001-01-09 -0.968689 -0.700311 1.024988 -0.705764 0.804285 -0.337177
2001-01-11 1.249893 -0.613356 1.975736 -0.093838 0.428004 0.634204
2001-01-15 0.430000 0.502100 0.194092 0.588685 -0.507332 1.404635
2001-01-17 1.005721 0.604771 -2.296667 0.157201 1.583537 1.359332
g h
2001-01-05 -1.183528 1.260880
2001-01-09 0.352487 0.700853
2001-01-11 1.060694 0.040667
2001-01-15 -0.044510 0.565152
2001-01-17 -0.731624 -0.331027
个人考虑
因为这是一个更大的应用程序,我将有任意数量的DataFrame 我想要:
- 使用现有的
pandas功能而不是构建我自己的 hack,即reduce( map ( ) )等。 - 返回
DataFrame的交叉点的视图,而不是创建DataFrame的副本
【问题讨论】:
标签: python pandas merge concat