gpt4 book ai didi

python - 在进行矢量化计算时如何处理类型错误?

转载 作者:行者123 更新时间:2023-12-03 08:21:00 27 4
gpt4 key购买 nike

我想避免在使用pandas数据帧(python-3.6)执行矢量化计算时发生崩溃。

例如,我有一个带有2列A,B的数据框。我想创建一个将为C = A-B的列C。但是,列A中的一个单元格是一个字符串,这会导致TypeError。看看下面的图片。

dataframe example

C列是我想要实现的结果。

当前,我收到类型错误消息:

TypeError: unsupported operand type(s) for -: 'float' and 'str'

这是预期的。

最佳答案

numpy.select 是可能的,但是在输出中得到混合值:

df = pd.DataFrame({
'A':[7,8,9,10,5],
'B':[1,2,3,'str',np.nan],
})

b = pd.to_numeric(df['B'], errors='coerce')
df['C'] = np.select([df['B'].isna(), b.isna()], [np.nan, 'ERROR'], default=df['A'] - b)
print (df)
A B C
0 7 1 6.0
1 8 2 6.0
2 9 3 6.0
3 10 str ERROR
4 5 NaN nan

最好通过 to_numeric 转换为数字,并仅在以后需要处理列时才减去:
b = pd.to_numeric(df['B'], errors='coerce')
df['C'] = df['A'] - b
print (df)
A B C
0 7 1 6.0
1 8 2 6.0
2 9 3 6.0
3 10 str NaN
4 5 NaN NaN

关于python - 在进行矢量化计算时如何处理类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053197/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com