亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

創建具有多個可變條件的新數據框并提取失敗的原因 - pandas

創建具有多個可變條件的新數據框并提取失敗的原因 - pandas

PHP
aluckdog 2023-11-09 15:41:24
我有下面的代碼??紤]到以下限制,我想創建如下輸出:A > 5,B > 4,C > 3如果不滿足條件,我想讀取數據框中的下面一行,存儲數據,并創建一個名為“失敗原因”的新列,其中列出 A、B 或 C 是否失敗。然后我希望腳本也報告通過的數據幀的行的“X”、“Y”和“Z”的相應值。此后,腳本應按“組”分組并顯示每組的最大“Hs”。我真的很難在數據框中使用多個變量來完成這項工作...任何幫助將不勝感激所需輸出   Group   Hs Fail Reason    X    Y     Z0      1  1.0      [A, B]  0.9  1.9  0.541      2  0.5   [A, B, C]  0.8  2.7  0.43主要代碼- 我當前的嘗試import pandas as pddata = [[1,0.5,8,8,8,0.85,1.64,0.5],        [1,1,8,8,8,0.9,1.9,0.54],        [1,1.5,0,0,10,1.1,2.0,0.74],        [2,0.5,6,5,4,0.8,2.7,0.43],        [2,1,1,1,1,0.9,2.9,0.45],        [2,1.5,1,2,1,1.1,3.1,0.47]]columns = ['Group', 'Hs', 'A', 'B', 'C', 'X', 'Y', 'Z']df = pd.DataFrame(data=data, columns=columns)Limit_A = 5Limit_B = 4Limit_C = 3# Opens an empty dataframe for appendingdf_new = pd.DataFrame(columns=['Group', 'Hs'])groups = df['Group'].unique()# for g in groupsfor g in groups:    # Create new temp dataframe    df_1 = df[df['Group'] == g]    # Input conditions, checks the columns one by one are NOT EQUAL TO ZERO. Outputs boolean values.    pass_criteria = (df_1['A'] > Limit_A) & (df_1['B'] > Limit_B) & (df_1['C'] > Limit_C)    # PASSES DATAFRAME. Locates rows where the conditions of mask_1 are SATISFIED and creates another temp dataframe.    df_passes = df_1.loc[pass_criteria]    # Find the max value in the dataframe e.g. the greatest operational wave height    max_num = df_passes['Hs'].max()    # Does the opposite of mask_1    fail_criteria = (df_1['A'] < Limit_A) & (df_1['B'] < Limit_B) &(df_1['C'] < Limit_C)    # FAILED DATAFRAME. Locates rows where the conditions of pass_criteria are SATISFIED and creates another temp dataframe.    df_fails = df_1.loc[fail_criteria]    # Uses the dataframe with FAIL and mkes the value_vars rows in the melted dataframe    melted = pd.melt(df_fails, value_vars=['A', 'B', 'C'])print(df_new)
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

IIUC 首先將 A、B、C 列與您的限制進行比較,然后agg返回map結果:


res = df[["A","B","C"]]>[5,4,3]


s = (pd.concat([df, (~res[~res.all(1)]).agg(lambda x: res.columns[x].tolist(),

                                              axis=1).rename("Fail reason")], axis=1)

       .dropna().drop_duplicates("Group").set_index("Group")["Fail reason"])


print (df.assign(failed_reason=df["Group"].map(s))

         .loc[res.all(1)].sort_values(["Group", "Hs"])

         .drop_duplicates("Group", keep="last"))


   Group   Hs  A  B  C    X    Y     Z failed_reason

1      1  1.0  8  8  8  0.9  1.9  0.54        [A, B]

3      2  0.5  6  5  4  0.8  2.7  0.43     [A, B, C]



查看完整回答
反對 回復 2023-11-09
  • 1 回答
  • 0 關注
  • 164 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號