在具有索引和列值作为输入的pandas数据帧上应用逐元素函数

gra*_*ham 2 pandas

我经常有这种需要,似乎无法找到有效地做到这一点的方法.

假设我有一个pandas DataFrame对象,我希望每个元素的值(i,j)等于f(index[i], columns[j]).

使用applymap,每个元素的索引和列的值将丢失.

最好的方法是什么?

piR*_*red 5

这取决于你要特别做的事情.

聪明的黑客
使用pd.Panel.apply
它是有效的,因为它将沿着主轴和次轴迭代每个系列.它的名字将是我们需要的元组.

df = pd.DataFrame(index=range(5), columns=range(5))

def f1(x):
    n = x.name
    return n[0] + n[1] ** 2

pd.Panel(dict(A=df)).apply(f1, 0)

   0  1  2   3   4
0  0  1  4   9  16
1  1  2  5  10  17
2  2  3  6  11  18
3  3  4  7  12  19
4  4  5  8  13  20
Run Code Online (Sandbox Code Playgroud)

示例1
这是一个这样的用例和该用例的一种可能的解决方案

df = pd.DataFrame(index=range(5), columns=range(5))

f = lambda x: x[0] + x[1]

s = df.stack(dropna=False)
s.loc[:] = s.index.map(f)
s.unstack()

   0  1  2  3  4
0  0  1  2  3  4
1  1  2  3  4  5
2  2  3  4  5  6
3  3  4  5  6  7
4  4  5  6  7  8
Run Code Online (Sandbox Code Playgroud)

或者这会做同样的事情

df.stack(dropna=False).to_frame().apply(lambda x: f(x.name), 1).unstack()
Run Code Online (Sandbox Code Playgroud)

例2

df = pd.DataFrame(index=list('abcd'), columns=list('xyz'))

v = df.values
c = df.columns.values
i = df.index.values

pd.DataFrame(
    (np.tile(i, len(c)) + c.repeat(len(i))).reshape(v.shape),
    i, c
)

    x   y   z
a  ax  bx  cx
b  dx  ay  by
c  cy  dy  az
d  bz  cz  dz
Run Code Online (Sandbox Code Playgroud)