【问题标题】:How to handle typeErrors when doing vectorize calculations?进行矢量化计算时如何处理 typeErrors?
【发布时间】:2019-11-24 22:48:33
【问题描述】:

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

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

C 列是我想要达到的结果。

目前我收到一条类型错误消息:

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

这是预期的。

【问题讨论】:

    标签: python pandas dataframe error-handling vectorization


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2020-07-31
      相关资源
      最近更新 更多