If you came here looking for information on how to merge a
DataFrame
andSeries
on the index, please look at this answer.The OP's original intention was to ask how to assign series elements as columns to another DataFrame. If you are interested in knowing the answer to this, look at the accepted answer by EdChum.
我能想到的最好的办法是
df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]}) # see EDIT below
s = pd.Series({'s1':5, 's2':6})
for name in s.index:
df[name] = s[name]
a b s1 s2
0 1 3 5 6
1 2 4 5 6
有谁能推荐更好的语法/更快的方法吗?
我的尝试:
df.merge(s)
AttributeError: 'Series' object has no attribute 'columns'
以及
df.join(s)
ValueError: Other Series must have a name
编辑发布的前两个答案突出显示了我的问题,因此请使用以下内容构造df
:
df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6])
最终结果
a b s1 s2
3 NaN 4 5 6
5 2 5 5 6
6 3 6 5 6
有一种方法:
把这里发生的事情分解。。。
pd.DataFrame(s).T
从s
创建单行数据帧,如下所示:接下来,
join
将这个新帧与df
连接起来:最后,索引1处的
NaN
值使用fillna
和forward fill(ffill
)参数填充列中的前一个值:为了避免使用
fillna
,可以使用pd.concat
重复由s
构造的数据帧行。在这种情况下,一般的解决方案是:下面是另一个解决编辑问题中的索引问题的解决方案:
s
通过重复值和整形(指定“Fortran”顺序)并传入适当的列名和索引,转换为数据帧。然后这个新的数据帧被连接到df
。更新
从v0.24.0开始,只要序列名为,就可以在DataFrame和Series上合并。
现在,您只需使用to_frame()将序列转换为数据帧即可。所以(如果加入索引):
您可以从序列构造一个数据帧,然后与该数据帧合并。 因此,将数据指定为值,但将其乘以长度,将列设置为索引,并将左索引和右索引的参数设置为True:
编辑如果希望序列中构造的df的索引使用df的索引,则可以执行以下操作:
这假设索引与长度匹配。
相关问题 更多 >
编程相关推荐