[英]Append two Pandas series to a dataframe by columns
I have a dataframe and two Pandas Series ac and cc, i want to append this two series as column. 我有一个数据帧和两个Pandas系列ac和cc,我想将这两个系列作为列附加。 But the problem is that my dataframe has a time index and Series as integer 但问题是我的数据帧有时间索引,系列为整数
A='a'
cc = pd.Series(np.zeros(len(A)*20))
ac = pd.Series(np.random.randn(10))
I try this but I had an empty dataframe 我试试这个,但我有一个空的数据帧
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))
The final result should be something like this : 最终结果应该是这样的:
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
... ... ...
It's not a problem if we always have NaN in the final result. 如果我们在最终结果中总是有NaN,那不是问题。
EDIT: 编辑:
After the answer of @piRSquared , i have to add a loop but i got an error in the keys : 在@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().
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.