如何合并序列和数据帧

2024-04-25 12:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

If you came here looking for information on how to merge a DataFrame and Series 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

Tags: thetoanswernameyoudataframedffor
3条回答

有一种方法:

df.join(pd.DataFrame(s).T).fillna(method='ffill')

把这里发生的事情分解。。。

pd.DataFrame(s).Ts创建单行数据帧,如下所示:

   s1  s2
0   5   6

接下来,join将这个新帧与df连接起来:

   a  b  s1  s2
0  1  3   5   6
1  2  4 NaN NaN

最后,索引1处的NaN值使用fillna和forward fill(ffill)参数填充列中的前一个值:

   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

为了避免使用fillna,可以使用pd.concat重复由s构造的数据帧行。在这种情况下,一般的解决方案是:

df.join(pd.concat([pd.DataFrame(s).T] * len(df), ignore_index=True))

下面是另一个解决编辑问题中的索引问题的解决方案:

df.join(pd.DataFrame(s.repeat(len(df)).values.reshape((len(df), -1), order='F'), 
        columns=s.index, 
        index=df.index))

s通过重复值和整形(指定“Fortran”顺序)并传入适当的列名和索引,转换为数据帧。然后这个新的数据帧被连接到df

更新
从v0.24.0开始,只要序列名为,就可以在DataFrame和Series上合并。

df.merge(s.rename('new'), left_index=True, right_index=True)
# If series is already named,
# df.merge(s, left_index=True, right_index=True)

现在,您只需使用to_frame()将序列转换为数据帧即可。所以(如果加入索引):

df.merge(s.to_frame(), left_index=True, right_index=True)

您可以从序列构造一个数据帧,然后与该数据帧合并。 因此,将数据指定为值,但将其乘以长度,将列设置为索引,并将左索引和右索引的参数设置为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的索引,则可以执行以下操作:

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

这假设索引与长度匹配。

相关问题 更多 >