'Dropping rows from a df rises a SettingWithCopyWarning error (Pandas, Python) when value doesn't exist (using inplace=T)?
I am trying to drop some rows based on a specific value of a dataframe:
dd = {'ae': pd.DataFrame(dict(a=[1,2,4], b=[4,5,6])),
'be': pd.DataFrame(dict(a=[13,21,413], b=[456,54,62]))}
def test_remove(dd, val):
test = dd.get('ae')
test.drop(test.loc[test['a']==val].index, inplace=True)
test_remove(dd, 24242)
But I am getting the following error:
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/frame.py:4906: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
Please advise what is wrong here? I have a dictionary of dataframes, I am trying to get into each of them and remove a row based on a specific column value.
Solution 1:[1]
Rather than doing the remove in place, it would be better to do something like this:
dd = {'ae': pd.DataFrame(dict(a=[1,2,4], b=[4,5,6])),
'be': pd.DataFrame(dict(a=[13,21,413], b=[456,54,62]))}
def remove_rows(dd, key, val, col):
dd[key] = dd[key].drop(dd[key].loc[dd[key][col]==val].index)
return dd
dd = remove_rows(dd, 'ae', 413, 'a')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | OD1995 |
