【问题标题】:If and function in pandas熊猫中的 if 和函数
【发布时间】: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"

感谢您的帮助

【问题讨论】:

标签: python pandas if-statement


【解决方案1】:

通过np.select()尝试:

#import numpy as np

conditions=[
    df['combined'] == "Real Estate_20",
    df['combined'] == "Real Estate_30"
]
labels=["Real Estate Loan","Home Mortgage Loan"]
df['v_purpose'] =np.select(conditions,labels,default='others')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2015-10-12
    • 2018-07-02
    • 1970-01-01
    • 2022-01-10
    • 2018-09-20
    • 2022-01-02
    相关资源
    最近更新 更多