[英]How to set values in a Pandas DataFrame Column equal to values based on another DataFrame
[英]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
兩個效率說明:
您需要使用 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.