gpt4 book ai didi

python numpy 创建数据集列 : only add value based on condition otherwise null

转载 作者:行者123 更新时间:2023-12-01 12:03:54 27 4
gpt4 key购买 nike

我尝试创建列终止日期。但只有当标志取消或失效设置为是时,列终止日期才应包含生效日期,否则为空。对于这三种方法,我收到以下错误消息。

df['Termination_Date'] = np.where((df['Cancellations'] == 'Yes') | (df['Lapses'] == 'Yes'), df['Effective Date'])
ValueError: either both or neither of x and y should be given

df['Termination_Date'] = np.where((df['Cancellations'] == 'Yes') | (df['Lapses'] == 'Yes'), df['Effective Date'], "")
TypeError: invalid type promotion

df['Termination_Date'] = np.where((df['Cancellations'] == 'Yes') | (df['Lapses'] == 'Yes'), df['Effective Date'], np.nan)
TypeError: invalid type promotion

谢谢

最佳答案

可以与 Series.where 一起使用?

示例:

df = pd.DataFrame({
'Effective Date':pd.date_range('2019-01-01', periods=6),
'Cancellations':['Yes'] * 4 + ['No'] * 2,
'Lapses':['yes'] * 2 + ['No'] * 4,

})

df['Termination_Date'] = df['Effective Date'].where((df['Cancellations'] == 'Yes') |
(df['Lapses'] == 'Yes'))

或者:

m = (df['Cancellations'] == 'Yes') | (df['Lapses'] == 'Yes')
df.loc[m, 'Termination_Date'] = df['Effective Date']

print (df)
Effective Date Cancellations Lapses Termination_Date
0 2019-01-01 Yes yes 2019-01-01
1 2019-01-02 Yes yes 2019-01-02
2 2019-01-03 Yes No 2019-01-03
3 2019-01-04 Yes No 2019-01-04
4 2019-01-05 No No NaT
5 2019-01-06 No No NaT

关于python numpy 创建数据集列 : only add value based on condition otherwise null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662334/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com