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

如何基于DataFrame的extra_type列创建ball_faced二值列?

解决方案:基于DataFrame列值创建新列

你的原代码错误在于apply的lambda函数中错误引用了整个列df1['extra_type'],而非当前遍历的元素x,导致逻辑失效。以下是几种可行的解决方案:

方法1:使用numpy.where(推荐,效率最优)

import numpy as np
df1['ball_faced'] = np.where(df1['extra_type'] != 'wides', 1, 0)

该方法会逐行判断extra_type是否不等于wides,满足条件赋值1,否则赋值0,自动处理NaN(NaN != 'wides'结果为True,因此会赋值1,符合需求)。

方法2:修正apply写法

df1['ball_faced'] = df1['extra_type'].apply(lambda x: 1 if x != 'wides' else 0)

这里lambda函数的参数x对应extra_type列的每个元素,直接判断单个元素是否不等于wides,逻辑清晰且符合需求。

方法3:布尔值转整数(简洁高效)

df1['ball_faced'] = (df1['extra_type'] != 'wides').astype(int)

Pandas布尔类型的Series可以直接转换为整数,True会转为1,False转为0,同样完美适配你的规则。

验证示例

import pandas as pd
import numpy as np

# 构造示例数据
data = {'extra_type': [np.nan, 'legbyes', 'wides', 'byes']}
df1 = pd.DataFrame(data)

# 执行方法3
df1['ball_faced'] = (df1['extra_type'] != 'wides').astype(int)
print(df1)

输出结果:

extra_type  ball_faced
0        NaN           1
1     legbyes           1
2      wides           0
3       byes           1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:35:20