将向量减去到数据帧的每一行

将向量减去到数据帧的每一行

本文介绍了将向量减去到数据帧的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框如下:

fruits = pd.DataFrame({'orange': [10, 20], 'apple': [30, 40], 'banana': [50, 60]})


   apple  banana  orange
0     30      50      10
1     40      60      20

我有这个向量(它也是一个数据帧)

And I have this vector (its also a dataframe)

sold = pd.DataFrame({'orange': [1], 'apple': [2], 'banana': [3]})

   apple  banana  orange
0      2       3       1

我想将此向量减去初始数据帧的每一行,以获得一个看起来像这样的数据帧

I want to subtract this vector to each row of the initial dataframe to obtain a dataframe which looks like this

   apple  banana  orange
0   28.0    47.0     9.0
1   38.0    57.0     19.0

我尝试过:

print fruits.subtract(sold, axis = 0)

输出为

   apple  banana  orange
0   28.0    47.0     9.0
1    NaN     NaN     NaN

它仅适用于第一行.我可以为每个行创建一个填充有矢量的数据框.有没有更有效的方法可以减去这个向量?我不想使用循环.

It worked only for the first line. I could create a dataframe filled with the vector for each row. Is there a more efficient way to subtract this vector ? I don't want to use a loop.

推荐答案

尝试:

fruits.sub(sold.iloc[0, :])

您之前尝试过的操作不起作用,因为sold是一个数据帧,并且减法将尝试同时对齐columnsindex. sold.iloc[0, :]位于第一行,因此是一个系列,因此将按您的预期工作.

What you tried before didn't work because sold is a dataframe and the subtraction will try to align both columns and index. sold.iloc[0, :] gets at the first row and is a series thus will work as you intended.

这篇关于将向量减去到数据帧的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:59