Reputation: 477
I have the following two dataframes:
test=pd.DataFrame({"x":[1,2,3,4,5],"y":[6,7,8,9,0]})
test2=pd.DataFrame({"z":[1],"p":[6]})
which result respectively in:
x y
0 1 6
1 2 7
2 3 8
3 4 9
4 5 0
and
z p
0 1 6
What is the best way to create a column "s" in table test that is equal to:
test["s"]=test["x"]*test2["z"]+test2["p"]
when I try the above expression I get the following output:
x y s
0 1 6 7.0
1 2 7 NaN
2 3 8 NaN
3 4 9 NaN
4 5 0 NaN
but I want the result along all the rows. I have researched something about the apply method or so called vectorized operations but I don't really know how to undertake the problem.
Expected output:
x y s
0 1 6 7.0
1 2 7 8.0
2 3 8 9.0
3 4 9 10.0
4 5 0 11.0
Thanks in advance
Upvotes: 0
Views: 52
Reputation: 4487
Use scalar multiplication, like this:
test['s'] = test.x * test2.z[0] + test2.p[0]
Upvotes: 1
Reputation: 351
Here is my solution, I took Trenton_M suggestions.
test=pd.DataFrame({"x":[1,2,3,4,5],"y":[6,7,8,9,0]})
test2=pd.DataFrame({"z":[1],"p":[6]})
Multiplication process:
test["s"] = test['x'] * test2.z.loc[0] + test2.p.loc[0]
test
Output:
x y s
0 1 6 7
1 2 7 8
2 3 8 9
3 4 9 10
4 5 0 11
Upvotes: 1