简体   繁体   English

如何使用 function 中的行索引和单元格值应用于 dataframe?

[英]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.

相关问题 如何根据应用的 function 索引 dataframe? -熊猫 - How to Index a dataframe based on an applied function? -Pandas 如何使用应用于每行索引的用户自定义函数派生的值填充Pandas数据帧列? - How to fill a Pandas dataframe column with values derived from a user-made function applied to the index of every row? 如何按单元格值获取数据框列索引 - how to get dataframe column index by cell value 在Python中应用函数后,如何更改数据帧的索引? - How to change the index of a dataframe after a function is applied in Python? Pandas 重塑数据框,其中每一行都是单元格值和索引 - Pandas reshape dataframe where each row is cell value and index DataFrame:如何根据行的另一个单元格切换单元格值? - DataFrame: How to toggle a cell value base on another cell of the row? 如何使用行中单元格的值来选择在 pandas dataframe 中查找列名? - How can I use the value of a cell in a row to chose find a column name in a pandas dataframe? 如何使用 str.contains function 使用行的索引替换单元格值 - How to replace a cell value using str.contains function using the index of the row xlwings:如何引用单元格并将该单元格中的值用作行范围值 - xlwings: how to reference a cell and use the value in that cell as a row range value Function 使用 str 索引获取 dataframe 的行值 - Function to get row Value of a dataframe using str Index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM