I have the following function to check if a row within a DataFrame contains a string. This approach does work however it will only match if the provided string is exactly the same as what is in the DataFrame and I need it to match if it contains a string.
e.g. searching for 'fox' in 'a quick brown fox' will yield no return
def search_excel_files(file_list, search_term):
#list of row indexes that contain the search term
rows = {}
for file in file_list:
df = pd.read_excel("files/" + file)
for row in df.iterrows():
if search_term in row[1].values:
#get row index
row_index = row[0]
#add row index to dictionary
rows = df.iloc[row_index].to_dict()
return rows
How can I check if the row contains the provided string in this instance?
if row[1].str.contains(search_term, regex=False).any():returns the errorCan only use .str accessor with string values!how can I access the value as a string?df['column_name'].str.contains(....). Your code iterates over the rows, thus operates on single values (row[1]).Can only use .str accessor with string values!when looping through the 'column_name' usingfor col in df.columns:any idea why that could be?None, or is of integer type or floating point), then it obviously fails. That should be obvious from the error message.