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

Pandas DataFrame两列相减存新列报错及列类型疑问

Fixing the Subtraction Error & Answering Your Series Question

Hey there! Let's tackle your two questions step by step:

1. Fixing the "unsupported operand type(s) for -: 'int' and 'str'" Error

The error tells us exactly what's going on: your manual input column is stored as a string (object) type, while the recommended column is an integer type. Pandas can't subtract a string from an integer directly—so we need to convert the string column to a numeric type first.

Here's the step-by-step fix:

  • First, confirm the data types of your columns to be 100% sure:
    print(df.dtypes)
    
    You’ll see manual input listed as object (which is pandas' way of saying "string").
  • Convert the manual input column to a numeric type. Use pd.to_numeric()—add errors='coerce' to turn any non-numeric values (like random text) into NaN (you can handle these missing values later if needed):
    import pandas as pd
    df['manual input'] = pd.to_numeric(df['manual input'], errors='coerce')
    
  • Now you can run your subtraction without errors, either way you tried before:
    # Direct subtraction
    df['available'] = df['recommended'] - df['manual input']
    
    # Using the .sub() method
    df['available'] = df['recommended'].sub(df['manual input'])
    
    If you end up with NaN values from the conversion, you can fill them with a default (like 0) using df['available'] = df['available'].fillna(0)—adjust this based on what makes sense for your data.

2. Does accessing a DataFrame column return a Series?

Yep, it sure does! When you use syntax like df['column_name'] (or df.column_name, if your column name has no spaces or special characters), pandas returns a pandas Series object. You can check this yourself with:

print(type(df['recommended']))
# Output: <class 'pandas.core.series.Series'>

If you want to get a single-column DataFrame instead of a Series, just use double square brackets:

single_col_df = df[['recommended']]
print(type(single_col_df))
# Output: <class 'pandas.core.frame.DataFrame'>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:47:50