You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame按选定行的值匹配转换为布尔型DataFrame

将Pandas DataFrame转换为与指定行值匹配的布尔型DataFrame

需求:把Pandas DataFrame转换为布尔型DataFrame,转换规则为每列的每个元素与指定行对应列的值匹配,相等则返回True,否则返回False。

输入示例

import pandas as pd

df = pd.DataFrame({'word1': ['The', 'A', 'The', 'A'],
                   'word2': ['cat', 'cat', 'dog', 'dog'],
                   'word3': ['ran', 'sat', 'sat', 'ate']})
print(df)

原始DataFrame输出:

word1 word2 word3
0   The   cat   ran
1     A   cat   sat
2   The   dog   sat
3     A   dog   ate

实现方案

以行0作为匹配基准,用以下两种简洁方法即可完成转换:

方法1:使用比较运算符==

df_result = df == df.loc[0]
print(df_result)

方法2:使用eq()方法(语义化更清晰)

df_result = df.eq(df.loc[0])
print(df_result)

预期输出

word1  word2  word3
0   True   True   True
1  False   True  False
2   True  False  False
3  False  False  False

内容的提问来源于stack exchange,提问作者user987443

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 05:07:02