本文介绍了获取dataframe的所有单元格作为(索引,列)的元组以传递给df.apply()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到Pandas数据框中每个单元格的索引和列名。

I want to get index and column name of every cell in the Pandas data frame.

例如,在从下面的代码生成的数据框中

For example, in data frame generated from the code below

df = pd.DataFrame({1 : np.arange(1, 6), 
               2 : np.arange(6, 11),
               3 : np.arange(11, 16),
               4 : np.arange(16, 21),
               5 : np.arange(21, 26)}, 
              index=[1, 2, 3, 4, 5])

我想访问值的行索引和值的列名称的索引/列名称组合,例如[1,1]表示1,[2,1]表示2,[3,1]表示3等...

I want to access an index/column name combination of value's row index and value's column name such as [1,1] for 1, [2,1] for 2, [3,1] for 3 etc...

最终目标是使用df.apply()根据数据框中数据框中的位置更新数据框中的每个值。需要索引和列名称(nxn数据框中的等效和有序标识符)从另一个数据框中提取值。

Ultimate goal is to update every value in the data frame based on its position within the data frame with df.apply(). Index and column names (equivalent and ordered identifiers in n x n data frame) are needed to pull values from another data frame.

谢谢!

推荐答案

我建议使用自己的函数来做到这一点。您可以使用类似dict的表示法访问数据框的每一列。除了通过访问所需的索引/行获取所需的元素,我将使用 .ix ,如下所示

I would suggest using a own function for doing that. You can access each column of the dataframe by using the dict-like notation. In addition to get the desired element by accessing the needed index/row I would use .ix as shown below

import pandas as pd

df = pd.DataFrame({1 : np.arange(1, 6), 
               2 : np.arange(6, 11),
               3 : np.arange(11, 16),
               4 : np.arange(16, 21),
               5 : np.arange(21, 26)}, 
              index=[1, 2, 3, 4, 5])

def get_from_coords(df, x, y):
    return df[x].ix[y]

例如:

In [2]: get_from_coords(df, 2, 1)
Out[2]: 6

文档提供了有关比并查找所需的条目/值。如果在行中找到该值,则包含索引和列名称的元组将存储到最后返回的列表中。我在第一个函数中提供了一种逐步的解决方案,并在列表理解中使用了一个生成器。

I am iterating through all the rows of the dataframe using .itertuples() which is faster than .iterrows() and looking for the desired entry/value. If the value is found in the row a tuple containing the index and column name is stored to a list which is returned at the end. I provided a kind of step-by-step solution in the first function and a one-liner using a generator in list comprehension.

编辑,因为OP指出他需要使用列名和索引名来更改相应的值:

假设我们要查找所有值 6 并将其替换为 66

Let's say we want to find all values 6 and replace them with 66:

for item in look_using_generator(df, 6):
    df[item[0]].ix[item[1]] = 66

这篇关于获取dataframe的所有单元格作为(索引,列)的元组以传递给df.apply()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:01