按列将两个Pandas系列附加到一个数据框

编程入门 行业动态 更新时间:2024-10-28 10:21:32
本文介绍了按列将两个Pandas系列附加到一个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数据框和两个Pandas系列ac和cc,我想将这两个系列附加为列.但是问题是我的数据帧有一个时间索引,并且Series为整数

I have a dataframe and two Pandas Series ac and cc, i want to append this two series as column. 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 ... ... ...

如果最终结果中始终包含NaN,这不是问题.

It's not a problem if we always have NaN in the final result.

在回答@piRSquared之后,我必须添加一个循环,但是键中出现错误:

After the answer of @piRSquared , i have to add a loop but i got an error in the keys :

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

更多推荐

按列将两个Pandas系列附加到一个数据框

本文发布于:2023-11-22 00:39:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615300.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   系列   数据   按列将   Pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!