
`np.select` 在处理多条件判断时,默认只返回第一个匹配的结果,无法同时输出所有符合条件的标签。本文将介绍一种利用 pandas 和 numpy 的 `dot` 方法,将行级别所有符合条件的标签高效地连接起来,从而实现对 dataframe 多条件判断结果的全面整合,并提供详细的实现步骤和代码示例。
在数据分析和处理中,我们经常需要根据多组条件对 DataFrame 的每一行进行分类或标记。Pandas 提供了 np.select 函数,它能够根据一系列条件和对应的选择值来生成一个新的 Series。然而,np.select 的一个限制是,它只会返回满足条件的 第一个 选择值。这意味着如果一行数据同时满足多个条件,np.select 只能给出其中一个结果,而无法将所有符合条件的标签合并输出。
考虑以下 DataFrame 和一组条件及对应的选择:
import pandas as pd
import numpy as np
df = pd.DataFrame({'cond1':[True, True, False, True],
'cond2':[False, False, True, True],
'cond3':[True, False, False, True],
'value': [1, 3, 3, 6]})
conditions = [df['cond1'] & (df['value']>4), # 条件1
df['cond2'], # 条件2
df['cond2'] & (df['value']>2), # 条件3
df['cond3'] & df['cond2']] # 条件4
choices = [ '1', '2', '3', '4']
df["class"] = np.select(conditions, choices, default=np.nan)
print("使用 np.select 的结果:")
print(df)上述代码的输出如下:
使用 np.select 的结果: cond1 cond2 cond3 value class 0 True False True 1 nan 1 True False False 3 nan 2 False True False 3 2 3 True True True 6 1
观察第2行(索引为2):cond2 为 True,且 value 为 3。此时,conditions[1] (即 df['cond2']) 为 True,conditions[2] (即 df['cond2'] & (df['value']>2)) 也为 True。根据 choices,它们分别对应 '2' 和 '3'。np.select 优先返回了 '2'。
再看第3行(索引为3):cond1, cond2, cond3 均为 True,value 为 6。
我们期望的结果是:
cond1 cond2 cond3 value class 0 True False True 1 nan 1 True False False 3 nan 2 False True False 3 2 and 3 3 True True True 6 1 and 2 and 3 and 4
显然,np.select 无法满足这种将所有匹配项联合输出的需求。
为了实现将所有符合条件的标签连接起来,我们可以巧妙地利用 Pandas DataFrame 的 dot 方法(其底层是 NumPy 的 np.dot)。核心思想是将布尔条件转换为一个 DataFrame,然后与处理过的选择标签进行“点乘”,从而实现字符串的条件拼接。
构建布尔条件 DataFrame: 首先,我们需要将 conditions 列表转换为一个 DataFrame。这个 DataFrame 的行索引将与原始 DataFrame 的行索引相同,列索引则对应 choices 中的标签。DataFrame 的每个单元格将是一个布尔值,表示该行是否满足对应的条件。
# 示例中的 conditions 是一个列表,包含多个布尔 Series
# 将其转换为 DataFrame,行索引是原始 df 的索引,列索引是 choices
df_conditions = pd.DataFrame(conditions, index=choices).T
print("转换后的布尔条件 DataFrame (df_conditions):")
print(df_conditions)df_conditions 的输出将是:
转换后的布尔条件 DataFrame (df_conditions):
1 2 3 4
0 False False False False
1 False False False False
2 False True True False
3 True True True True这个 DataFrame 直观地展示了每一行(索引)分别满足哪些条件(列)。
准备连接字符串: 为了在 dot 操作中实现字符串拼接,我们需要将 choices 列表中的每个标签后面加上连接符(例如 " and ")。
# 将 choices 转换为 Series,并在每个元素后添加 ' and '
choice_strings = pd.Series([c + ' and ' for c in choices], index=choices)
print("\n准备好的选择字符串 (choice_strings):")
print(choice_strings)choice_strings 的输出将是:
准备好的选择字符串 (choice_strings): 1 1 and 2 2 and 3 3 and 4 4 and dtype: object
执行 dot 乘法并清理: 现在,我们可以将 df_conditions 与 choice_strings 进行 dot 乘法。在 Pandas 中,当对一个布尔 DataFrame 和一个字符串 Series 或列表进行 dot 操作时,True 会被视为 1,False 会被视为 0。它会沿着共同的索引(这里是 df_conditions 的列索引和 choice_strings 的索引)进行“乘法”和“求和”操作。对于字符串而言,这意味着如果布尔值为 True,则对应的字符串会被“累加”(即拼接)。
# 执行 dot 乘法
combined_classes = df_conditions.dot(choice_strings)
print("\nDot 乘法后的结果 (combined_classes):")
print(combined_classes)combined_classes 的输出将是:
Dot 乘法后的结果 (combined_classes): 0 1 2 2 and 3 and 3 1 and 2 and 3 and 4 and dtype: object
可以看到,每行的所有匹配标签都被拼接起来了,但末尾多了一个 " and "。
最后,使用 str.strip(' and ') 方法移除每个字符串末尾多余的连接符。
df['class'] = combined_classes.str.strip(' and ')
print("\n最终结果 DataFrame:")
print(df)最终输出:
最终结果 DataFrame: cond1 cond2 cond3 value class 0 True False True 1 1 True False False 3 2 False True False 3 2 and 3 3 True True True 6 1 and 2 and 3 and 4
这与我们期望的结果完全一致。
import pandas as pd
import numpy as np
# 原始数据
df = pd.DataFrame({'cond1':[True, True, False, True],
'cond2':[False, False, True, True],
'cond3':[True, False, False, True],
'value': [1, 3, 3, 6]})
# 定义条件和选择
conditions = [df['cond1'] & (df['value']>4),
df['cond2'],
df['cond2'] & (df['value']>2),
df['cond3'] & df['cond2']]
choices = [ '1', '2', '3', '4']
# 1. 将条件转换为布尔 DataFrame,行索引为原始 df 的索引,列索引为 choices
df_conditions = pd.DataFrame(conditions, index=choices).T
# 2. 准备连接字符串:在每个 choice 后添加 ' and '
choice_strings = pd.Series([c + ' and ' for c in choices], index=choices)
# 3. 执行 dot 乘法,然后清理末尾的 ' and '
df['class'] = df_conditions.dot(choice_strings).str.strip(' and ')
# 额外处理:如果需要将空字符串替换为 np.nan
# df['class'] = df['class'].replace('', np.nan)
print("最终的 DataFrame 结果:")
print(df)当 np.select 无法满足多条件联合输出的需求时,通过将布尔条件转换为 DataFrame,并利用 Pandas 的 dot 方法与带有连接符的选择标签进行“点乘”,可以优雅且高效地实现所有匹配条件的字符串拼接。这种方法为处理复杂的多条件分类问题提供了强大的灵活性,是 Pandas 数据处理中的一个高级技巧。
以上就是Pandas 中 np.select 多条件联合输出的实现技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号