user2988577
user2988577

Reputation: 4207

Change values over specific indexes in DataFrame

Let's say I have a Series of flags in a DataFrame:

a=pd.DataFrame({'flag':[0,1,0,0,1]})

and I want to change the values of the flags which are in a specific indexes:

lind=[0,1,3]

This is a simple solution:

def chnflg(series,ind):
   if series.ix[ind]==0:
       series.ix[ind]=1
   else:
       series.ix[ind]=0

map(partial(chnflg,a),lind)

It works fine but there are two issues: the first is that it makes the changes in-place, while I would like a new series in DataFrame. This is not a big deal after all.

The second point is that it does not seems pythonic enough. Is it possible to do better?

Upvotes: 2

Views: 97

Answers (2)

Andy Hayden
Andy Hayden

Reputation: 375485

An easier way to describe your function is as x -> 1 - x, this will be more efficient that apply/map.

In [11]: 1 - a.iloc[lind]
Out[11]: 
   flag
0     1
1     0
3     1

Note: I like to use iloc here as it's less ambiguous.

If you wanted to assign these inplace then do the explicit assignment:

In [12]: a.iloc[lind] = 1 - a.iloc[lind]

In [13]: a
Out[13]: 
   flag
0     1
1     0
2     0
3     1
4     1

Upvotes: 2

EdChum
EdChum

Reputation: 394041

You could create a dict that flips the values and call map, this would return a series and you can create a new dataframe and leave the original intact:

In [6]:

temp={0:1,1:0}

pd.DataFrame(a.ix[lind]['flag'].map(temp))

Out[6]:

   flag
0     1
1     0
3     1

Upvotes: 1

Related Questions