Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas: replace values based on location not index value

Tags:

python

pandas

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
like image 995
ramesh Avatar asked Aug 04 '16 20:08

ramesh


1 Answers

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'
like image 123
ayhan Avatar answered Sep 26 '22 05:09

ayhan