简体   繁体   中英

How to calculate new column to a dataframe using a linear equation python

I have an existing df that looks something like this:

Current Price     Contract Cost     GP %     New Contract Cost
  30.19               16.01         .47            16.75
  84.22               60.90         .28            57.12
  95.16               58.54         .39            57.12

I want to add a new column to the df called 'New Price' which will be an updated price of the item based off of the new contract cost, keeping GP % the same.

If I were going to solve this on paper I would do GP % = (x - New Contract Cost) / x where x is the new price.

Example from df: .47 = (x -16.75)/x

x = ~31.60

So in this example 'New Price' for row one would be 31.60

I have about 500 rows in the dataframe and don't want to manually calculate all of them.

How would I go about constructing the code for this? I'm very new to this and don't really know where to start. I work in sales and want to be able to quantify price changes based on new contract costs if we keep GP % the same. Thanks in advance.

Try, using pandas intrinsic data alignment there is no need to loop nor use lambda functions:

df['New Price'] = df['New Contract Cost']/(1-df['GP %'])

Output:

   Current Price  Contract Cost  GP %  New Contract Cost  New Price
0          30.19          16.01  0.47              16.75  31.603774
1          84.22          60.90  0.28              57.12  79.333333
2          95.16          58.54  0.39              57.12  93.639344
   df['New Price'] = df['New Contract Cost'] / (1 - df['GP%'].astype(float))

Should create a column 'New Price' in df based on your current values. This just simplified the algebra to contain only your 'New Price' variable on the left side of the equation. This simplified the algebra so 'New Price' was alone on the left hand side of the equation allowing for a dataframe implementation of the solution.

It'd be optimal to rearrange your formula in the following way.

New Price = - (New Contract Cost / (GP % - 1)), where GP %.= 1.

Then you can implement this in Python with the following:

import pandas as pd

df = pd.DataFrame({"Current Price":[30.19,84.22,95.16],
                   "Contract Cost":[16.01,60.90,58.54],
                   "GP %":[0.47,0.28,0.39],
                   "New Contract Cost":[16.75,57.12,57.12]})

df["New Price"] = -(df["New Contract Cost"] / (df["GP %"] - 1))
   Current Price  Contract Cost  GP %  New Contract Cost  New Price
0          30.19          16.01  0.47              16.75  31.603774
1          84.22          60.90  0.28              57.12  79.333333
2          95.16          58.54  0.39              57.12  93.639344

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