简体   繁体   English

将函数应用于熊猫数据框中的特定单元格

[英]apply function to specific cells in a pandas dataframe

I would like to apply a function to some cells in a pandas dataframe.我想对 Pandas 数据框中的某些单元格应用一个函数。 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).我存储了单元格索引(在 (col, row) 元组列表中,但我可以以任何格式存储,使这个问题更容易解决)。

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:我想应用my_func = lambda x : x+1 (编辑:或其他一些 my_func,例如my_func = lambda x : str(x) + str (x) +"!" ,我只是以这个为例因为很容易显示输出)到单元格索引[(0,1), (0,2), (1,2)]得到:

  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?有没有更好的方法来做到这一点然后在我的索引元组列表上运行dataframe.iat[col, row]=my_func(dataframe.iloc[col, row])循环?

(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...) (我想尝试创建一个函数,该函数会根据从列表创建的一组元组检查索引,并且仅在索引存在时才应用 my_func,但是apply是我能找到的唯一批量应用函数,它运行在一个轴上,不是逐个单元格,因此无法检查索引...)

Use the underlying numpy array:使用底层的numpy数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM