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

Pandas拆分DataFrame指定列字符串为两列时出现KeyError问题的求助

Fixing the KeyError When Splitting the type Column in Pandas

Hey there! Let's break down why your split operation is throwing a KeyError: 1 and how to fix it properly.

What's Causing the KeyError?

The error happens because some rows in your type column don't contain the / separator. When you use str.split('/', n=1, expand=True) on those rows, the result only has one value (no subcategory), so the generated DataFrame only has column 0—there's no column 1 to assign to df["subcat"], hence the KeyError.

First, let's verify this by checking which rows are missing the /:

# Find rows where 'type' doesn't have a '/'
rows_without_slash = df[~df['type'].str.contains('/')]
print(rows_without_slash)

The Correct Way to Split & Assign Columns

To handle both rows with and without the separator, we can split directly into the new columns and fill any missing subcategories with a default value (like 'No Subcategory') if needed:

# Split the 'type' column into two new columns in one step
df[['main_cat', 'subcat']] = df['type'].str.split('/', n=1, expand=True)

# Fill NaN values in 'subcat' (from rows without '/') with a default value
df['subcat'] = df['subcat'].fillna('No Subcategory')

# Check the result
df.head()

Why Your First Attempt Only Gave One Column

If your first df.column.str.split('/',n=1, expand = True) only returned one column, that's also because some rows lack the /—Pandas will only create as many columns as the maximum number of splits across all rows. If all rows only had one part (no /), you'd only get column 0.

Optional: Filter Out Rows Without Separators

If you don't want rows that lack the / in your DataFrame, you can filter them out first:

# Keep only rows where 'type' contains '/'
df = df[df['type'].str.contains('/')]

# Now split safely
df[['main_cat', 'subcat']] = df['type'].str.split('/', n=1, expand=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:32:47