我有一个问题,需要把多个时间序列合并到一个共同的DataFrame中。以下是我使用的示例代码:
import pandas
import datetime
import numpy as np
start = datetime.datetime(2001, 1, 1)
end = datetime.datetime(2001, 1, 10)
dates = pandas.date_range(start, end)
serie_1 = pandas.Series(np.random.randn(10), index = dates)
start = datetime.datetime(2001, 1, 2)
end = datetime.datetime(2001, 1, 11)
dates = pandas.date_range(start, end)
serie_2 = pandas.Series(np.random.randn(10), index = dates)
start = datetime.datetime(2001, 1, 3)
end = datetime.datetime(2001, 1, 12)
dates = pandas.date_range(start, end)
serie_3 = pandas.Series(np.random.randn(10), index = dates)
print 'serie_1'
print serie_1
print 'serie_2'
print serie_2
print 'serie_3'
print serie_3
serie_4 = pandas.concat([serie_1,serie_2], join='outer', axis = 1)
print 'serie_4'
print serie_4
serie_5 = pandas.concat([serie_4, serie_3], join='outer', axis = 1)
print 'serie_5'
print serie_5
这导致我在 serie_5(第二个concat)中出现了错误:
Traceback (most recent call last):
File "C:\Users\User\Workspaces\Python\Source\TestingPandas.py", line 29, in <module>
serie_5 = pandas.concat([serie_4, serie_3], join='outer', axis = 1)
File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 878, in concat
verify_integrity=verify_integrity)
File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 948, in __init__
self.new_axes = self._get_new_axes()
File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 1101, in _get_new_axes
new_axes[i] = self._get_comb_axis(i)
File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 1125, in _get_comb_axis
all_indexes = [x._data.axes[i] for x in self.objs]
AttributeError: 'TimeSeries' object has no attribute '_data'
我愿意让结果看起来像这样(第二列有随机值):
0 1 2
2001-01-01 -1.224602 NaN NaN
2001-01-02 -1.747710 -2.618369 NaN
2001-01-03 -0.608578 -0.030674 -1.335857
2001-01-04 1.503808 -0.050492 1.086147
2001-01-05 0.593152 0.834805 -1.310452
2001-01-06 -0.156984 0.208565 -0.972561
2001-01-07 0.650264 -0.340086 1.562101
2001-01-08 -0.063765 -0.250005 -0.508458
2001-01-09 -1.092656 -1.589261 -0.481741
2001-01-10 0.640306 0.333527 -0.111668
2001-01-11 NaN -1.159637 0.110722
2001-01-12 NaN NaN -0.409387
问题出在哪里?就像我说的,可能很基础,但我还是想不出来,因为我是初学者...
serie_5 = pandas.concat([serie_1, serie_2, serie_3], join='outer', axis=1)
对我的系列不起作用? 它返回错误:无法从重复的轴重新索引 实际上,我的系列(mySeries)和此处使用的系列一样都是_pandas.core.series.Series_, 但我的系列还有第二个规格。您建议我提出另一个问题吗? - SPSpd.concat
会引发ValueError: cannot reindex from a duplicate axis
。为了解决这个问题,将每个系列转换为DataFrame(例如s = s.reset_index()
),然后在“index”列上外部合并数据框:(例如functools.reduce(lambda left,right: pd.merge(left,right,on='index',how='outer'), [s.reset_index() for s in [serie_1, serier_2, serie_3]])
)。 - unutbu