繁体   English   中英

根据条件将 boolean 值分配给新列

[英]Assigning boolean value to a new column based on conditions

我需要根据名为X ( 1,2,3,4 , 5 ) 的列的值将 boolean 值分配给新列Y中的行。 我在数据集df中有此列:

X
1
1
1
3
2
5
2
4
1

我想要一个新的 Y,在一个新的数据集中,它是 df 的副本,其中:

  • 如果行的 X 值 = 1,则为 True
  • 如果行的 X 值 = 2,则为 False
  • 如果行的 X 值 = 3,则为 False
  • 如果行的 X 值 = 4,则为 True
  • 如果行的 X 值 = 5,则为 False

所以我应该有

X        Y
1      true
1      true
1      true
3      false
2      false
5      false
2      false
4      true
1      true

我写了这段代码:

new_df=df.copy()
new_df['Y'] = False
for index in df.iterrows():
    if   df['X'] == 1:
        new_df.iloc[index,9] = True
    elif df['X'] == 2:
        new_df.iloc[index,9] = False
    elif df['X'] == 3:
        new_df.iloc[index,9] = False
    elif df['X'] == 4:
        new_df.iloc[index,9] = True
    else:
        new_df.iloc[index,9] = False

收到此错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

你能帮我修复代码以获得预期的 output 吗? 谢谢

编辑: np.where() 优于 map()

我相信您需要做的是创建一个自定义 function ,您可以在其中使用if-elif-else然后使用map 类似于以下内容:

def evaluator(x):
   if x == 1:
      return True
   elif x == 2:
      return False
   elif x == 3:
      return False
   elif x == 4: 
      return True
   else:
      return False
df['Y'] = df['X'].map(lambda x: evaluator(x))

@Allolz 注释提供了有用的简化,它还可以允许使用带有np.where()的矢量化操作

df['Y'] = np.where(df['X'].isin([1,4]),True,False) 

在您的情况下,根据您的输入 dataframe,输出:

   X      Y
0  1   True
1  1   True
2  1   True
3  3  False
4  2  False
5  5  False
6  2  False
7  4   True
8  1   True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM