【发布时间】:2021-07-19 13:50:19
【问题描述】:
我是 python 的新手,我正在尝试为我的案例找到像 If 和 elif 这样的东西。我的代码如下:
import pandas as pd
df = pd.DataFrame({'v_contract_number': ['VN120001438','VN120001439',
'VN120001440','VN120001438',
'VN120001439','VN120001440'],
'Collateral': ['Real Estate','Real Estate','Gold','Gold','Deposit','Deposit'],
'Purpose': [20,30,20,30,20,30]})
# df
v_contract_number Collateral Purpose
0 VN120001438 Real Estate 20
1 VN120001439 Real Estate 30
2 VN120001440 Gold 20
3 VN120001438 Gold 30
4 VN120001439 Deposit 20
cols = ['Collateral', 'Purpose']
df['combined'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
df['v_purpose'] = df['combined'].apply(lambda x:'Real Estate Loan' if x == "Real Estate_20" else 'Others')
df.head()
#df
v_contract_number Collateral Purpose combined v_purpose
0 VN120001438 Real Estate 20 Real Estate_20 Real Estate Loan
1 VN120001439 Real Estate 30 Real Estate_30 Others
2 VN120001440 Gold 20 Gold_20 Others
3 VN120001438 Gold 30 Gold_30 Others
4 VN120001439 Deposit 20 Deposit_20 Others
但我想为组合列添加更多条件,例如:
if df['combined'] == "Real Estate_20":
df['v_purpose'] == "Real Estate Loan"
elif df['combined'] == "Real Estate_30":
df['v_purpose'] == "Home Mortgage Loan"
else
df['v_purpose'] == "Others"
感谢您的帮助
【问题讨论】:
-
使用
np.where或df.mask。
标签: python pandas if-statement