簡體   English   中英

根據其他兩列的值,在 pandas 中創建一個新列

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

我有一個示例數據:

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]

我想要一個名為 action 的新列,它假設: 1 如果 column1 值低於 3 和高於 5,否則 df.column2.any(axis=1) 值。

示例 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

使用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