簡體   English   中英

根據兩列值相等,將列中的字段設置為 0 Pandas

[英]Set Field in Column to 0 Based on Two Column Values Being Equal Pandas

我有一個使用 pandas 的 df 和許可證列表,然后是子許可證列表。 我需要比較 Parent 和 Sub Permit 列,如果 Parent Permit 等於 sub permit,則將 Value total 字段設置為 0。 BLD-00045 行本質上需要保留 70000 值,但 ELE 和 PM 需要設置為0。這可能嗎?

Parent Permit    Sub Permit    Value Total
BLD-00045         NaN          70000
ELE-2019         BLD-00045     100
PLM-2019         BLD-00045     200

我想要的 output 是這個

Parent Permit    Sub Permit    Value Total
BLD-00045        NaN           70000
ELE-2019        BLD-00045      0
PLM-2019        BLD-00045      0

在您的數據行之間閱讀,我猜測實際上存在某種分層的、樹狀的許可證結構,並且您對僅將成本分配到某些級別感興趣。

根據您的示例,聽起來您想要識別子許可證等於任何父許可證的行。

您可能想嘗試這樣的事情:

parent_permits = df['Parent Permit'].unique()
has_sub_permit = df['Sub Permit'].isin(parent_permits)
df.loc[has_sub_permit, 'Value Total'] = 0

兩個效率說明:

  • 如果您需要反復檢查此條件,您可以考慮在數據框中添加“有父級”列。
  • 如果許可類型本質上是分類的,您可以考慮對這些列使用 pandas 的分類數據類型 Pandas 然后將使用整數存儲值,這可能會加快操作速度。

您需要使用 function 來檢查每一行的x["Sub Permit"]值與x["Parent Permit"]中的所有內容。 如果“Sub Permit”在“Parent Permit”中的任何位置(我假設在哪里都沒有關系),則將該值設置為0 ,否則使用“Sub Permit”行的x["Value Total"]的原始值

您可以使用df.apply()方法將此方法應用於 DataFrame 中的每一行。 要將其作為單行執行,請使用 Python lambda

import pandas as pd

print(df)
print("---------__")
# lambda x: <return some value> if <x is condition> else <return some other value> 
df["Value Total"] = df.apply(lambda x: # use df.apply() to apply a lambda where x will be each row in the df
                             0 # Return this if True
                             if x["Sub Permit"] in # If the value of is ine Series created by...
                             df["Parent Permit"].unique() # All the unique values of df["Parent Permit"] 
                             else x["Value Total"], # otherwise return the original value found in else x["Value Total"] 
                             axis=1 #Use axis=1 (rows) and not axis=0 (columns
                             )
print(df)

OUTPUT:

Parent Permit Sub Permit  Value Total
0     BLD-00045        NaN        70000
1      ELE-2019  BLD-00045          100
2      PLM-2019  BLD-00046          200
---------__
Parent Permit Sub Permit  Value Total
0     BLD-00045        NaN        70000
1      ELE-2019  BLD-00045            0
2      PLM-2019  BLD-00046          200

這應該這樣做。

list_of_parent_permits = x['Parent Permit'].tolist()
df['Value Total'] = df.apply(lambda x: 0 if x['Sub Permit'] in list_of_parent_permits else x['Value Total'], axis = 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM