Python DataFrames 创建3个其他 “True / False” 列的“Create / False”列

2024-06-26 14:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用金融数据框来处理这个问题。我想创建一个df['LB4']列,如果LB1、LB2和LB3都为true,则返回true

Date        Open    High    Low     Close    Volume     LB1     LB2     LB3                             
2005-01-03  4.63    4.65    4.47    4.52    173354034   False   False   False
2005-01-04  4.56    4.68    4.50    4.57    274515332   False   False   False
2005-01-05  4.60    4.66    4.58    4.61    170210264   False   False   True
2005-01-06  4.62    4.64    4.52    4.61    176469496   False   True    True
2005-01-07  4.64    4.97    4.62    4.95    558932752   True    True    False

有什么想法吗

我是Python新手,希望能得到任何帮助

谢谢


Tags: 数据falsetruedfclosedateopen金融
1条回答
网友
1楼 · 发布于 2024-06-26 14:09:50

从这个开始(稍微修改一下你的例子):

In [1095]: df
Out[1095]: 
     LB1    LB2    LB3
0  False  False  False
1  False  False  False
2  False  False   True
3   True   True   True
4   True   True   True

您可以使用按位&

In [1096]: df.LB1 & df.LB2 & df.LB3
Out[1096]: 
0    False
1    False
2    False
3     True
4     True
dtype: bool

或者,使用df.all

In [1097]: df[['LB%d' %i for i in range(1, 4)]].all(axis=1)
Out[1097]: 
0    False
1    False
2    False
3     True
4     True
dtype: bool

如果您只知道那些列是布尔的,而不知道其他的,那么您可以将列表理解缩短为df.select_dtypes([bool]).all(axis=1)

相关问题 更多 >