Here is my df:
In[12]: df = pd.DataFrame(data = list("aabbcc"), columns = ["s"], index=range(11,17))
In[13]: df
Out[13]:
s
11 a
12 a
13 b
14 b
15 c
16 c
Let's try to replace values based on index:
In[14]: df.loc[11, "s"] = 'A'
In[15]: df
Out[15]:
s
11 A
12 a
13 b
14 b
15 c
16 c
In[16]: df.ix[12, "s"] = 'B'
In[17]: df
Out[17]:
s
11 A
12 B
13 b
14 b
15 c
16 c
It works! But if I do the same based on position, not index, say something like this, but it shows ValueError (ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]
):
In[18]: df.iloc[1, "s"] = 'b'
And, if I try something like this:
df.s.iloc[1] = "b"
I get this warning :
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
You can use get_loc to get the location of the column and pass that to iloc:
df.iloc[1, df.columns.get_loc('s')] = 'B'
df
Out:
s
11 a
12 B
13 b
14 b
15 c
16 c
Or the other way around:
df.loc[df.index[1], 's'] = 'B'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With