Pandas拆分DataFrame指定列字符串为两列时出现KeyError问题的求助
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

