简体   繁体   中英

Create a new column based on other columns in existing dataframes

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

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

使用标量乘法 ,如下所示:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM