[英]How to use a row value and a row value plus a number in a conditional statement to find the max of a column based on the grouping
以前,我使用以下代碼根據后續行中的值創建值。
demo["NFdat"] = demo.groupby('NID')['Fdat'].shift(-1)
此代碼將下一行中的“Fdat”分配給按 NID 和 Fdat 分組的當前行中的“NFdat”。
我想做類似的事情,在當前行中為變量分配來自共享相同“ID”但來自下一個奶牛泌乳的后續行的最大值。 有效乳酸+1
示例數據如下所示。 我想確定后續泌乳 (Lact) 中的最大 Lact_xmast 值,並將該值存儲在新變量 Next_Lact_max_xmast 中。
NID Lact Lact_xmast
770 207018229 2 1
771 207018229 2 1
772 207018229 3 1
773 207018229 3 1
774 207018229 3 1
775 207018229 3 2
776 207018229 4 1
777 207018229 4 1
778 207018229 4 2
779 207018229 4 2
780 207018229 4 3
781 207018229 4 3
782 207018229 4 3
我想實現的 output 是
NID Lact Lact_xmast Next_Lact_max_xmast
770 207018229 2 1 2
771 207018229 2 1 2
772 207018229 3 1 3
773 207018229 3 1 3
774 207018229 3 1 3
775 207018229 3 2 3
776 207018229 4 1 NA
777 207018229 4 1 NA
778 207018229 4 2 NA
779 207018229 4 2 NA
780 207018229 4 3 NA
781 207018229 4 3 NA
782 207018229 4 3 NA
這是一種方法:
# For current lactation, get max Lact_xmast for next lactation
max_lact_xmas = df.groupby('Lact')['Lact_xmast'].max().shift(-1)
# Left join the resulting max_lact_xmas Series to original dataframe.
# For the merge condition, we use column from the original dataframe and index from series.
df.merge(max_lact_xmas, left_on='Lact', right_index=True, how='left')
NID Lact Lact_xmast_x Lact_xmast_y
770 207018229 2 1 2.0
771 207018229 2 1 2.0
772 207018229 3 1 3.0
773 207018229 3 1 3.0
774 207018229 3 1 3.0
775 207018229 3 2 3.0
776 207018229 4 1 NaN
777 207018229 4 1 NaN
778 207018229 4 2 NaN
779 207018229 4 2 NaN
780 207018229 4 3 NaN
781 207018229 4 3 NaN
782 207018229 4 3 NaN
排序“Lact”值只是為了更清潔(不需要):
df["Lact"] = df["Lact"].sort_values(ascending=True)
創建 Label 用於加入“Lact”+1:
df["NextLact"] = df["Lact"] + 1
計算每個“Lact_xmast”的最大值:
df_grouped = df.groupby(["Lact"], as_index=False).Lact_xmast.max()\
.rename(columns={"Lact_xmast":"Next_Lact_max_xmast", "Lact":"NextLact"})
在摸索“Lact_xmast”的最大值上加入 NextLact:
df.merge(df_grouped, on="NextLact", how="left")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.