python - 函数未按预期运行 - 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
非常感谢!
解决方案
我不太确定我的问题是否正确,但我会试一试。这是您可以尝试的
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
####################################################################
推荐阅读
- xaml - 添加 XAML 自定义用户控件不会在 Visual Studio 中添加 idl 文件
- javascript - 在悬停和移动元素时继续调用函数
- c# - 从richTextBox到.pdf文件的文本c#:希腊字符不会出现在.pdf文件中
- java - 关闭 NameNode - 如何启动 hadoop 的本地主机?
- javascript - PouchDB - 在函数中调用 get() ( TypeError: cb is not a function )
- c++ - 如何将一行二维字符串向量提取为双精度向量?
- linux - 当合成器关闭时,Qt::WA_TranslucentBackground 不起作用
- linux - 如何从 bash find exec 命令中获取两个输出
- javascript - 即使使用切片,数组的副本也会更改原始数组
- node.js - 无效的 ELF 标头 - Argon2 包