简体   繁体   English

根据其他两列的值,在 pandas 中创建一个新列

[英]Create a new column in pandas depending on values from two other columns

I have an example data as:我有一个示例数据:

datetime    column1.   column2 
2020-01-01.   5.       [0,0,0,1]
2020-01-02.   4.       [0,0,0,0]
2020-01-03.   10.      [1,1,1,0]
2020-01-04.   2.       [1,1,1,1]

I want a new column called action which assumes: 1 if column1 values are below 3 and above 5 otherwise the df.column2.any(axis=1) values.我想要一个名为 action 的新列,它假设: 1 如果 column1 值低于 3 和高于 5,否则 df.column2.any(axis=1) 值。

The example output should look like this:示例 output 应如下所示:

datetime    column1.   column2    action
2020-01-01.   5.       [0,0,0,1].  1
2020-01-02.   2.       [0,0,0,0].  1
2020-01-03.   10.      [1,1,1,0].  1
2020-01-04.   4.       [0,0,0,0]   0

Use numpy.where Series.between with any :使用numpy.where Series.betweenany

df['action'] = np.where(df.column1.between(3,5), df.column2.apply(any), 1)
print (df)
     datetime  column1       column2  action
0  2020-01-01        5  [0, 0, 0, 1]       1
1  2020-01-02        2  [0, 0, 0, 0]       1
2  2020-01-03       10  [1, 1, 1, 0]       1
3  2020-01-04        4  [0, 0, 0, 0]       0

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

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