Pandas DataFrame两列相减存新列报错及列类型疑问
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:
You’ll seeprint(df.dtypes)manual inputlisted asobject(which is pandas' way of saying "string"). - Convert the
manual inputcolumn to a numeric type. Usepd.to_numeric()—adderrors='coerce'to turn any non-numeric values (like random text) intoNaN(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:
If you end up with# Direct subtraction df['available'] = df['recommended'] - df['manual input'] # Using the .sub() method df['available'] = df['recommended'].sub(df['manual input'])NaNvalues from the conversion, you can fill them with a default (like 0) usingdf['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

