如何匹配DataFrame另一列字符串?解决str.contains报错问题
Hey there! Let's break down why you're hitting this error and how to fix it quickly.
Why the Error Happens
When you run dataframe1['title'].str.contains(dataframe1['color']), you're trying to pass an entire Series (dataframe1['color']) to the str.contains() method. But here's the catch: str.contains() is built to work with a single string or regex pattern, not an entire column of values. Since Series are mutable (you can change their contents after creating them), they can't be "hashed"—a requirement for how str.contains() processes its input behind the scenes. That's exactly why you're seeing that TypeError.
The Fix: Check Row-by-Row
Instead of passing the whole Series, we need to check each row individually—comparing the color value in that row to the title value in the same row. The easiest way to do this is with Pandas' apply() method:
Basic Version
dataframe1['contains_color'] = dataframe1.apply( lambda row: row['color'] in row['title'], axis=1 )
This code loops through each row (axis=1 means we're working row-wise), grabs the color and title values for that row, and checks if the color is present in the title. It then adds a new column contains_color with True/False results.
Case-Insensitive Check (Optional)
If you want to ignore uppercase/lowercase differences (like matching "Red" in "red shirt"), tweak the code to normalize the case:
dataframe1['contains_color'] = dataframe1.apply( lambda row: row['color'].lower() in row['title'].lower(), axis=1 )
Handle Missing Values (Optional)
If your color column has missing values (NaN), you'll want to handle those to avoid errors. Here's how:
import pandas as pd def check_color_in_title(row): # Return False if color is missing, otherwise check the title if pd.isna(row['color']): return False return row['color'] in row['title'] dataframe1['contains_color'] = dataframe1.apply(check_color_in_title, axis=1)
Why This Works
By using apply(axis=1), we're working with individual row values instead of entire Series. Each row's color is a single string (or NaN), which the in operator can handle perfectly without any hashing issues.
内容的提问来源于stack exchange,提问作者Musakkhir Sayyed

