'Getting SettingWithCopyWarning with iloc or loc when some filtering is done on the dataframe wit regex [duplicate]

I have the following statement to compute the mean of three quiz scores and create a new column based on the computed mean:

scores.loc[:, 'Average'] = scores[['Quiz1', 'Quiz2', 'Quiz3']].mean(axis=1).round(2)

However this leads to the following warning:

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

After the dataframe is changed with the following set of operations, this warning shows up:

pattern = r'(?:^|\D)(\d{7})(?!\d)'
regex = re.compile(pattern)
scores = scores[scores['StudentId'].apply(lambda x: (regex.search(x) != None))]
scores

Any ideas why this filtering based on regex causes this error?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source