![](/img/trans.png)
[英]Creating a new column in dataframe based on multiple conditions from other rows and columns? Including rows that are null? - Python/Pandas
[英]Creating a new column in the pandas dataframe depend on the other columns in the same dataframe but different rows
我是 python 的新手。
我遇到了一個問題,我需要在 dataframe 中創建一個新列,這取決於同一 dataframe 中的其他列但不同的行。
df = pd.DataFrame({"Year":[2011,2014,2012,2013],"Value1":[10,40,20,30],"Value2":[10,100,30,60]})
df
Year Value1 Value2 Product
0 2011 10 10 1
1 2014 40 100 1
2 2012 20 30 1
3 2013 30 60 1
4 2011 10 10 2
5 2014 40 100 2
6 2012 20 30 2
7 2013 30 60 2
8 2011 10 10 3
9 2014 40 100 3
10 2012 20 30 3
11 2013 30 60 3
我想根據今年的值和去年創建一個新列,新列 value3 應該成為這個和去年的 value1 和 value2 之間差異的商,例如,2012 年行的 value3 應該由 ( 30-10)/(20-10) = 2。
所以我預期的新 dataframe 應該是這樣的:
Year Value1 Value2 Product Value3
0 2011 10 10 1 NaN
1 2014 40 100 1 4.0
2 2012 20 30 1 2.0
3 2013 30 60 1 3.0
4 2011 10 10 2 NaN
5 2014 40 100 2 4.0
6 2012 20 30 2 2.0
7 2013 30 60 2 3.0
8 2011 10 10 3 NaN
9 2014 40 100 3 4.0
10 2012 20 30 3 2.0
11 2013 30 60 3 3.0
有人能幫我嗎?
我嘗試使用 for 循環獲取 dataframe 的每一行,但我發現很難獲得去年的數據,因為它沒有排序。
首先sort_values
on Year
,使用shift
進行計算,然后sort_index
保留原始順序:
print (df.sort_values("Year")
.assign(Value3=(df["Value2"]-df["Value2"].shift())/(df["Value1"]-df["Value1"].shift()))
.sort_index())
Year Value1 Value2 Value3
0 2011 10 10 NaN
1 2014 40 100 4.0
2 2012 20 30 2.0
3 2013 30 60 3.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.