[英]How to use row index and cell value in function applied to dataframe?
I have a table similar to this, with the blank spaces being empty strings and the numbers being floats:我有一个类似的表,空格是空字符串,数字是浮点数:
1 2 3 4 5 6
A
B 8 5
C 5 7
D 2 3 5
E 0
I want to replace the value of each cell with the output of a function which takes two arguments: the index of the row and the value of the cell.我想用 function 的 output 替换每个单元格的值,它需要两个 arguments:行的索引和单元格的值。
For example, the values in the first column should be replaced with the output of func(D, 2) and func(E, 0) and the empty cells should stay empty.例如,第一列中的值应替换为 func(D, 2) 和 func(E, 0) 的 output 并且空单元格应保持为空。 The function output is a string.
function output 是一个字符串。
Expected output table:预期 output 表:
if func(D, 2) returns X and func(E, 0) returns Y, then column 1 should look like:如果 func(D, 2) 返回 X 并且 func(E, 0) 返回 Y,则第 1 列应如下所示:
1 2 3 4 5 6
A
B 8 5
C 5 7
D X 3 5
E Y
How do I do this?我该怎么做呢?
First of all I would fill the dataframe:首先,我将填写 dataframe:
df.fillna(0, inplace=True)
then let's assume that your function is called func
and it's first argument is row index, you can apply it using the map
method while iterating over rows:然后让我们假设您的 function 被称为
func
并且它的第一个参数是行索引,您可以在迭代行时使用map
方法应用它:
for idx in df.index:
df.loc[idx] = df.loc[idx].map(lambda x: func(idx, x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.