[英]How to calculate new column to a dataframe using a linear equation python
我有一個看起來像這樣的現有 df:
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
我想在 df 中添加一個名為“新價格”的新列,這將是基於新合同成本的項目更新價格,保持 GP % 不變。
如果我要在紙面上解決這個問題,我會做GP % = (x - New Contract Cost) / x其中 x 是新價格。
來自 df 的示例: .47 = (x -16.75)/x
x = ~31.60
所以在這個例子中,第一行的“新價格”是 31.60
我在 dataframe 中有大約 500 行,不想手動計算所有行。
我 go 如何為此構建代碼? 我對此很陌生,真的不知道從哪里開始。 我從事銷售工作,如果我們保持 GP % 不變,我希望能夠根據新合同成本量化價格變化。 提前致謝。
嘗試使用 pandas 內部數據 alignment 無需循環,也無需使用 lambda 函數:
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))
應該根據您當前的值在 df 中創建一個“新價格”列。 這只是簡化了代數,使其僅包含等式左側的“新價格”變量。 這簡化了代數,因此“新價格”單獨出現在等式的左側,從而允許解決方案的 dataframe 實施。
最好按以下方式重新排列您的公式。
新價格 = -(新合同成本 /(GP % - 1)),其中 GP %.= 1。
然后您可以在 Python 中使用以下代碼實現:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.