gpt4 book ai didi

python - 根据 Python 中其他列的条件创建新列

转载 作者:行者123 更新时间:2023-11-28 22:12:30 25 4
gpt4 key购买 nike

我想在Python中做一些与this one中的问题非常相似的事情R 用户。我的目的是创建一个新列,其值是根据其他列的条件创建的

例如:

d = {'year': [2010, 2011,2013, 2014], 'PD': [0.5, 0.8, 0.9, np.nan], 'PD_thresh': [0.7, 0.8, 0.9, 0.7]}
df_temp = pd.DataFrame(data=d)

现在我想创建一个条件:

伪代码:

if for year X the value of PD is greater or equal to the value of PD_thresh
then set 0 in a new column y_pseudo

otherwise set 1

我的预期结果是这样的:

df_temp 
Out[57]:
year PD PD_thresh y_pseudo
0 2010 0.5 0.7 0.0
1 2011 0.6 0.7 0.0
2 2013 0.9 0.8 1.0
3 2014 NaN 0.7 NaN

最佳答案

使用numpy.selectisnage :

m1 = df_temp['PD'].isna()
m2 = df_temp['PD'].ge(df_temp['PD_thresh'])

df_temp['y_pseudo'] = np.select([m1, m2], [np.nan, 1], default=0)
print (df_temp)
year PD PD_thresh y_pseudo
0 2010 0.5 0.7 0.0
1 2011 0.6 0.8 0.0
2 2013 0.9 0.9 1.0
3 2014 NaN 0.7 NaN

另一个解决方案是将 True/False 映射到 1/0 的掩码转换为整数,并通过 notna 仅设置非缺失行。 :

m2 = df_temp['PD'].ge(df_temp['PD_thresh'])
m3 = df_temp['PD'].notna()

df_temp.loc[m3, 'y_pseudo'] = m2[m3].astype(int)
print (df_temp)
year PD PD_thresh y_pseudo
0 2010 0.5 0.7 0.0
1 2011 0.6 0.8 0.0
2 2013 0.9 0.9 1.0
3 2014 NaN 0.7 NaN

关于python - 根据 Python 中其他列的条件创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807503/

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