dWitty
dWitty

Reputation: 524

apply function to specific cells in a pandas dataframe

I would like to apply a function to some cells in a pandas dataframe. Not along a column or row axis, across the entire dataframe, but only some cells.

I have the cell indices stored (in a list of (col, row) tuples, but I can store in any format that would make this question more easily solved).

so for example if my dataframe is:

  0 1 2
0 1 2 1
1 2 1 3
2 0 0 1

I want to apply my_func = lambda x : x+1 (EDIT: or some other my_func, eg my_func = lambda x : str(x) + str (x) +"!", I'm just giving this one as an example because it's easy to show output) to cell indices [(0,1), (0,2), (1,2)] to get:

  0 1 2
0 1 2 1
1 3 1 3
2 1 1 1

is there any better way to do this then to run a loop of dataframe.iat[col, row]=my_func(dataframe.iloc[col, row]) on my list of index tuples?

(I wanted to try making a function that would check the index against a set of tuples created from the list, and only apply my_func if the index was there, but apply, the only bulk application function I could find, runs across an axis, not cell by cell, so there was no way to check the indices...)

Upvotes: 3

Views: 412

Answers (1)

user3483203
user3483203

Reputation: 51185

Use the underlying numpy array:

x, y = zip(*idx)
df.to_numpy()[y, x] += 1

   0  1  2
0  1  2  1
1  3  1  3
2  1  1  1

Upvotes: 1

Related Questions