2

I have two pandas dataframes in Python, one only has one row of data. The other has many rows. I would like to go through each row of the first one and subtract the second one from it. I would then like to store the results in a dataframe the size of the second one. The first one is

df1 = pd.DataFrame({"Amounts": [1.1, 2.2, 3.3]})

And the second one is

df2 = pd.DataFrame({"A": [500, 600, 700, 800, 900], 
                    "B": [250, 750, 900, 500, 200], 
                    "C": [450, 125, 600, 200, 800]})

I am trying to subtract one from the other (1.1 from A, 2.2 from B, 3.3 from C) to get the following output:

A     B    C
[498.9, 247.8, 446.7],
[598.9, 747.8, 121.7],
[698.9, 897.8, 596.7],
[798.9, 497.8, 196.7],
[898.9, 197.8, 796.7]

And save it as another dataframe. Any assistance you could provide would be very helpful!  Bonus points if you could also provide an answer for similar arithmetic (i.e. multplying instead of subtracting)

2 Answers 2

2

You need to convert df1 to Series and to numpy array to bypass index alignment:

df3 = df2.sub(df1['Amounts'].to_numpy(), axis=1)

There are many alternative, like full numpy:

df3 = df2.sub(df1.to_numpy().ravel(), axis=1)

Or full pandas:

df3 = df2.sub(df1['Amounts'].set_axis(df2.columns), axis=1)

output:

       A      B      C
0  498.9  247.8  446.7
1  598.9  747.8  121.7
2  698.9  897.8  596.7
3  798.9  497.8  196.7
4  898.9  197.8  796.7
Sign up to request clarification or add additional context in comments.

1 Comment

The full pandas option worked great, thanks! It also turns out there was an issue with the csv I was reading in for df2.
1
import pandas as pd
import numpy as np

df1 = pd.DataFrame({"Amounts": [1.1, 2.2, 3.3]})

df2 = pd.DataFrame({"A": [500, 600, 700, 800, 900], 
                "B": [250, 750, 900, 500, 200], 
                "C": [450, 125, 600, 200, 800]})

final = pd.DataFrame()
if len(df1) != len(df2.columns):
     pass
else:
   for i in range(len(df1)):
       final[df2.columns[i]]=df2[df2.columns[i]].astype(float)-df1['Amounts'] [i].astype(float)

final



   A    B   C
0   498.9   247.8   446.7
1   598.9   747.8   121.7
2   698.9   897.8   596.7
3   798.9   497.8   196.7
4   898.9   197.8   796.7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.