首页 > 解决方案 > 将带有参数的函数应用于数据帧

问题描述

我正在尝试将函数应用于数据框,其中参数来自数据框本身。有没有办法简洁地做到这一点?

df: 
    | a  | b  | c  | d |
A   | 20 | 15 | 33 | 5 |
B   | 5  | 6  | 10 | 8 |
C   | 10 | 15 | 5  | 10|

应用于每个单元格的函数

# c = sum of the current column
# r = sum of the current row 
# t = sum of all values
def calcIndex(x, c, r, t):
    return (x/c)*(t/r)*100

结果

    | a   | b   | c   | d   |
A   | 111 | 81  | 134 | 42  |
B   | 70  | 82  | 102 | 170 |
C   | 101 | 148 | 37  | 154 |

我已经尝试df.apply但不确定如何访问特定的行/列总数,具体取决于x正在计算的

标签: pythonpandasdataframe

解决方案


此处的问题DataFrame.apply可能是按列或按索引循环,而不是按两者循环,因此如果在一个函数中需要两者,则不能在此处使用。

更好更快的是在输出中使用带有和的矢量化函数DataFrame.div,最后使用with表示整数:DataFrame.mulDataFrame.sumDataFrame.roundDataFrame.astype

c = df.sum(axis=1)
r = df.sum()
t = r.sum()
df1 = df.div(c, axis=0).mul(t).div(r).mul(100).round().astype(int)
print (df1)
     a    b    c    d
A  111   81  134   42
B   70   82  102  170
C  101  148   37  154

为了提高性能,可以使用numpy

#pandas 0.24+
arr = df.to_numpy()
#pandas below
#arr = df.values
c = arr.sum(axis=1)
r = arr.sum(axis=0)
t = r.sum()
out = np.round(arr / c[:, None] * t / r * 100).astype(int)
df = pd.DataFrame(out, index=df.index, columns=df.columns)
print (df)
     a    b    c    d
A  111   81  134   42
B   70   82  102  170
C  101  148   37  154

推荐阅读