Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

python 2.7 - Subtract a vector to each row of a dataframe

My dataframe looks like this :

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

I tried :

print fruits.subtract(sold, axis = 0)

And the output is

   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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

convert the df to a series using squeeze and pass axis=1:

In [6]:
fruits.sub(sold.squeeze(), axis=1)

Out[6]:
   apple  banana  orange
0     28      47       9
1     38      57      19

The conversion is necessary as by design arithmetic operations between dfs will align on indices and columns, by passing a Series this allows you to subtract from each row in the df the row from the other df.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...