When I run this code
df = raw.copy() # making a copy of dataframe raw
df['new col'] = ''
for i in range(len(df)):
df['new col'].loc[i] = 'some thing'
I got this warning (warning 1):
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self._setitem_single_block(indexer, value, name)
Based on user aaossa's suggestion, I changed the code as follows
df = raw
df['new col'] = ''
for i in range(len(df)):
df.loc[i, 'new col'] = 'some thing'
I then get a similar SettingWithCopyWarning (warning 2) with an added tip:
<ipython-input-74-75e3db22bde6>:2: SettingWithCopyWarning:
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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df['new col'] = ''
SettingWithCopyWarning:
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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self._setitem_single_column(loc, value, pi)
The added tip in warning 2 Try using .loc[row_indexer,col_indexer] = value instead
came too late when I already implemented it (df.loc[i, 'new col'] = 'some thing'
).
My question are:
- why wasn't that relevant added tip included in warning 1, which would solve the problem at hand and help me to avoid a novice mistake
df = raw
in the second attempt with the modified code? - Why was that tip added in warning 2 when I already implemented (
df.loc[i, 'new col'] = 'some thing'
)? - What is
pi
in this opaque informationself._setitem_single_column(loc, value, pi)
. What does it mean?