0

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

6
  • 1
    What if test2 has more than one row? Commented Sep 17, 2019 at 20:35
  • please show your desired output..does test2 always have just one row? Commented Sep 17, 2019 at 20:35
  • I have updated my question with desired output. Yes, Test2 has always one row. Commented Sep 17, 2019 at 20:40
  • 1
    if test has always one row, then just use their values as scalars. Instant broadcasting, no need to worry about index matching etc. Simply test['x'] * test2['z'].item() + test2['p'].item() . I believe .item will be deprecated in next pandas version, so you can also simply use .loc[0] instead. Commented Sep 17, 2019 at 20:42
  • 1
    test['s'] = test.x * test2.z.loc[0] + test2.p.loc[0] Commented Sep 17, 2019 at 20:46

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

Use scalar multiplication, like this:

test['s'] = test.x * test2.z[0] + test2.p[0]

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.