简体   繁体   English

根据布尔条件在新列中设置值

[英]Set values in a new column based on a boolean condition

I have a data frame and two dictionaries as follows: 我有一个数据框和两个字典,如下所示:

a = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
x = {'a':'a'}
y = {'b':'b'}

Now I would like to perform an operation that adds a new column C such that each cell in C stores x when A >=2 and B >= 2, and stores y otherwise. 现在,我想执行一个添加新列C的操作,以便当A> = 2并且B> = 2时,C中的每个单元格都存储x,否则存储y。 The resulting data frame should be equivalent to: 结果数据帧应等效于:

a = pd.DataFrame({'A':[1,2,3],'B':[4,5,6], 'C':[{'b':'b'}, {'a':'a'}, {'a':'a'}]})

I have tried many different approaches and nothing has worked so far. 我尝试了许多不同的方法,但到目前为止没有任何效果。 This is a toy example, while the real data frame will have many rows and columns and more complex conditions might be used. 这是一个玩具示例,而实际数据帧将具有许多行和列,并且可能会使用更复杂的条件。 The end goal is to prepare a data frame for visualization with plotly by storing all the necessary info for visualization (such as marker definitions) as additional columns. 最终目标是通过将可视化所需的所有必要信息(例如标记定义)存储为其他列,从而为可可视化的可视化准备数据框架。

Thanks in advance. 提前致谢。

Using np.where 使用np.where

a['C'] = np.where((a.A >= 2) & (a.B >= 2), x, y)

   A  B           C
0  1  4  {'b': 'b'}
1  2  5  {'a': 'a'}
2  3  6  {'a': 'a'}

To explain this a bit since you say your real data is more complex, np.where will: 为了解释这一点,因为您说您的实际数据更复杂,请在np.where进行以下操作:

Return elements, either from x or y, depending on condition 根据条件从x或y返回元素

So simply create your condition, and then identify what x and y need to be based on the result of the condition. 因此,只需创建您的条件,然后根据条件的结果确定需要xy的值。 If you have more than two possible options, and multiple conditions, then you should look at np.select 如果您有两个以上的可能选项和多个条件,则应查看np.select

Here is the equivalent np.select for the sake of demonstration: 为了演示起见,这是等效的np.select

conds = [(a.A >=2) & (a.B >=2)]
choices = [x]

np.select(conds, choices, default=y)
# array([{'b': 'b'}, {'a': 'a'}, {'a': 'a'}], dtype=object)

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

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