首页 > 解决方案 > 函数未按预期运行 - 2 个参数,检查 bool 是否为 True

问题描述

我需要一个函数来逐行检查值是真还是假

(df['is_unique_ID'] 包含 True 或 False 值)。如果为 True,则需要返回另一列 df['etp'] 的(数字)值

def get_etp(self,per_id_u,etp):
    if per_id_u is True:
        return etp
    else:
        return "test"


df['new_col'] = df.apply(get_etp,args= (df['is_unique_ID'],df['etp']),axis=1)

不幸的是,它返回一个只有“test”作为值的列,而我知道 df['is_unique_ID'] 包含大约 4000 True 和 250 False

顺便说一句,这是一个更复杂函数的第 1 步,所以我会很感激继续使用 def 函数和 apply 的解决方案,因为我稍后会添加更多参数和 elif:

(not python code)
The full function will create new_col = 
1)  if is_unique_ID is True --> = ETP  
2)  if is_unique_ID is False --> 
2.1) if col_1 is True --> = ETP_2
2.2) if col_1 is False --> = ETP_3 


非常感谢!

标签: pythonpandasfunctionif-statement

解决方案


我不太确定我的问题是否正确,但我会试一试。这是您可以尝试的

import pandas as pd 
import numpy as np 

df1 = pd.DataFrame({'is unique': [False, True, True, False] , 'etp':[2, 5, 3, 4]},  index=None)

print(df1)
#    is unique  etp
0      False    2
1       True    5
2       True    3
3      False    4


print(df1[df1['is unique']])
#    is unique  etp
1       True    5
2       True    3

# If your intention is to create a new column, you can do so by doing the following:
df1['new_col'] = df1['etp'][df1['is unique']]
print(df1)

#   is unique  etp  new_col
0      False    2      NaN
1       True    5      5.0
2       True    3      3.0
3      False    4      NaN

编辑而不是跨行应用函数,您可以做的只是简单地查询并创建一个新的列行。

import pandas as pd 
import numpy as np 

df1 = pd.DataFrame({'is unique': [True, True, True, False] ,'col_1': [True, False, True, False] , 'etp':[2, 5, 3, 4],'etp2':[1, 0, 1, 0],'etp3':[1, 0, 1, 0]})

print(df1)
########################################
   is unique  col_1  etp  etp2  etp3
0       True   True    2     1     1
1       True  False    5     0     0
2       True   True    3     1     1
3      False  False    4     0     0
########################################

df1['new_col'] = df1['etp'][df1['is unique']]
df1['new_col1'] = df1['etp2'][df1['col_1']]
df1['new_col2'] = df1['etp3'][ ~df1['col_1']]
print(df1)

####################################################################
   is unique  col_1  etp  etp2  etp3  new_col  new_col1  new_col2
0       True   True    2     1     1      2.0       1.0       NaN
1       True  False    5     0     0      5.0       NaN       0.0
2       True   True    3     1     1      3.0       1.0       NaN
3      False  False    4     0     0      NaN       NaN       0.0
####################################################################

推荐阅读