如何合并Series和DataFrame [英] How to merge a Series and DataFrame

查看:1835
本文介绍了如何合并Series和DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您是来这里寻找有关方法的信息 合并索引上的DataFrameSeries ,请查看此 答案.

If you came here looking for information on how to merge a DataFrame and Series on the index, please look at this answer.

OP的初衷是询问如何分配系列元素 作为另一个DataFrame的列.如果您有兴趣了解 答案,请查看EdChum的接受的答案.

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.


我能想到的最好的是


Best I can come up with is

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

有人可以建议更好的语法/更快的方法吗?

Can anybody suggest better syntax / faster method?

我的尝试:

df.merge(s)
AttributeError: 'Series' object has no attribute 'columns'

df.join(s)
ValueError: Other Series must have a name

EDIT 发布的前两个答案突出了我的问题,因此请使用以下内容构造df:

EDIT The first two answers posted highlighted a problem with my question, so please use the following to construct 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

推荐答案

您可以从系列中构建一个数据框,然后与该数据框合并. 因此,您将数据指定为值,然后将它们乘以长度,将列设置为索引,并将left_index和right_index的参数设置为True:

You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:

In [27]:

df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
Out[27]:
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

编辑,如果您希望序列中构造的df的索引使用df的索引,则可以执行以下操作:

EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:

df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)

这假定索引与长度匹配.

This assumes that the indices match the length.

这篇关于如何合并Series和DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆