Python 按列将两个熊猫系列附加到数据帧
我有一个dataframe和两个Pandas系列ac和cc,我想将这两个系列附加为列。但问题是,我的数据帧有一个时间索引和整数序列Python 按列将两个熊猫系列附加到数据帧,python,pandas,Python,Pandas,我有一个dataframe和两个Pandas系列ac和cc,我想将这两个系列附加为列。但问题是,我的数据帧有一个时间索引和整数序列 A='a' cc = pd.Series(np.zeros(len(A)*20)) ac = pd.Series(np.random.randn(10)) 我尝试了这个,但是我有一个空的数据帧 index = pd.date_range(start=pd.datetime(2017, 1,1), end=pd.datetime(2017, 1, 2), fr
A='a'
cc = pd.Series(np.zeros(len(A)*20))
ac = pd.Series(np.random.randn(10))
我尝试了这个,但是我有一个空的数据帧
index = pd.date_range(start=pd.datetime(2017, 1,1), end=pd.datetime(2017, 1, 2), freq='1h')
df = pd.DataFrame(index=index)
df = df.join(pd.concat([pd.DataFrame(cc).T] * len(df), ignore_index=True))
df = df.join(pd.concat([pd.DataFrame(ac).T] * len(df), ignore_index=True))
最终结果应该是这样的:
cc ac
2017-01-01 00:00:00 1 0.247043
2017-01-01 01:00:00 1 -0.324868
2017-01-01 02:00:00 1 -0.004868
2017-01-01 03:00:00 1 0.047043
2017-01-01 04:00:00 1 -0.447043
2017-01-01 05:00:00 NaN NaN
... ... ...
如果我们在最终结果中总是有NaN,这不是问题
编辑: 在回答@piRSquared之后,我必须添加一个循环,但我在键中得到了一个错误:
az = [cc, ac]
for i in az:
df.join(
pd.concat(
[pd.Series(s.values, index[:len(s)]) for s in [i]],
axis=1, keys=[i]
)
)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我更新了我的问题@piRSquared,我在键上有一个错误。是的,编辑搞错了。无论你想做什么,最好从一个不同的问题开始。你只想在一路上迭代一系列连接它们的序列吗?是的,这是相同的原则,当我做keys=[i.all()]时,我有正确的答案,除了我的名字是真和假之外
df.join(
pd.concat(
[pd.Series(s.values, index[:len(s)]) for s in [cc, ac]],
axis=1, keys=['cc', 'ac']
)
)
cc ac
2017-01-01 00:00:00 0.0 -0.319653
2017-01-01 01:00:00 0.0 0.630061
2017-01-01 02:00:00 0.0 -1.648402
2017-01-01 03:00:00 0.0 -1.141017
2017-01-01 04:00:00 0.0 -0.643353
2017-01-01 05:00:00 0.0 0.718771
2017-01-01 06:00:00 0.0 0.379173
2017-01-01 07:00:00 0.0 1.799804
2017-01-01 08:00:00 0.0 0.883260
2017-01-01 09:00:00 0.0 0.788289
2017-01-01 10:00:00 0.0 NaN
2017-01-01 11:00:00 0.0 NaN
2017-01-01 12:00:00 0.0 NaN
2017-01-01 13:00:00 0.0 NaN
2017-01-01 14:00:00 0.0 NaN
2017-01-01 15:00:00 0.0 NaN
2017-01-01 16:00:00 0.0 NaN
2017-01-01 17:00:00 0.0 NaN
2017-01-01 18:00:00 0.0 NaN
2017-01-01 19:00:00 0.0 NaN
2017-01-01 20:00:00 NaN NaN
2017-01-01 21:00:00 NaN NaN
2017-01-01 22:00:00 NaN NaN
2017-01-01 23:00:00 NaN NaN
2017-01-02 00:00:00 NaN NaN