满足DataFrame条件时为变量赋值的Pandas代码报错求助
问题:筛选DataFrame符合条件的行并赋值给变量
需求说明
我想要实现的是:当DataFrame(df)满足指定条件时,将对应值赋给变量。
示例逻辑:
初始化变量:
local_bid = 0
筛选df中"Entity"列等于"Keyword"的行,然后将对应行的"Bid"列值赋给local_bid。
错误尝试代码
我尝试了以下代码:
df.loc[["Entity"] == "Keyword", local_bid] = df["Bid"]
报错信息
运行失败,报错如下:
Traceback (most recent call last): File "/home/shaumne/Desktop/zorba/Sp_limpr.py", line 17, in <module> s = limpr.loc[["Entity"] == "Keyword", local_bid] = limpr["Bid"] File "/home/shaumne/.local/lib/python3.10/site-packages/pandas/core/indexing.py", line 818, in __setitem__ iloc._setitem_with_indexer(indexer, value, self.name) File "/home/shaumne/.local/lib/python3.10/site-packages/pandas/core/indexing.py", line 1703, in _setitem_with_indexer key, _ = convert_missing_indexer(idx) File "/home/shaumne/.local/lib/python3.10/site-packages/pandas/core/indexing.py", line 2585, in convert_missing_indexer raise KeyError("cannot use a single bool to index into setitem") KeyError: 'cannot use a single bool to index into setitem'
错误原因分析
["Entity"] == "Keyword"是将列表与字符串比较,得到单个布尔值False,这不是pandas可识别的行筛选条件,导致索引器错误。- 代码逻辑混乱:
df.loc的正确用法是df.loc[行条件, 列名],但你把变量local_bid当作列名传入,且错误地试图修改df的值,而非将筛选结果赋值给local_bid。
正确实现方式
情况1:筛选结果只有一行
直接提取对应值赋值:
local_bid = 0 # 筛选Entity列等于Keyword的行,获取Bid列数据 filtered_data = df.loc[df["Entity"] == "Keyword", "Bid"] # 若有匹配数据,取第一个值 if not filtered_data.empty: local_bid = filtered_data.iloc[0]
情况2:筛选结果有多行
根据需求选择处理方式:
# 转为列表存储所有匹配的Bid值 local_bid_list = df.loc[df["Entity"] == "Keyword", "Bid"].tolist() # 或者计算平均值 average_bid = df.loc[df["Entity"] == "Keyword", "Bid"].mean()
内容的提问来源于stack exchange,提问作者Shamna Sama
相关产品推荐
相关产品推荐

