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
test2has more than one row?test2always have just one row?testhas always one row, then just use their values as scalars. Instant broadcasting, no need to worry about index matching etc. Simplytest['x'] * test2['z'].item() + test2['p'].item(). I believe.itemwill be deprecated in next pandas version, so you can also simply use.loc[0]instead.test['s'] = test.x * test2.z.loc[0] + test2.p.loc[0]