如何在 Python Pandas 中对同一数据框中的两列执行操作?

How to perform an operation with two columns in the same dataframe in Python Pandas?

我正在尝试应用操作 'x-y/y',作为 x'Faturamento'y'Custo' 来自名为 'df',并将结果存储在名为 'Roi'.

的新列中

我尝试使用应用功能:

df['Roi'] = df.apply(lambda x, y: x['Faturamento']-y['Custo']/y['Custo'], axis=1)

正在返回:

TypeError: () missing 1 required positional argument: 'y'

我该怎么做?

我想你的意思是:

df['Roi'] = df.apply(lambda x: (x['Faturamento']-x['Custo'])/x['Custo'], axis=1)

x 指数据帧

你可以只使用像简单算术这样的语法的列操作。 Pandas会自动为你对齐索引,让你每次操作都是逐行操作。

df['Roi'] = (df['Faturamento'] - df['Custo']) / df['Custo']

df['Roi'] = df['Faturamento'] / df['Custo'] - 1

这样,您就可以享受 Pandas 的快速矢量化处理,它已经优化为 运行 快速。如果你在 axis=1 上使用带有 lambda 函数的 .apply(),它只是底层处理中的一个慢 Python 循环,而且会很慢。

性能基准

测试 1。小 df 有 4 行

   Faturamento  Custo
0           50     20
1           10      5
2            5     15
3          100    400
%%timeit
df['Roi'] = df.apply(lambda x: (x['Faturamento']-x['Custo'])/x['Custo'], axis=1)

721 µs ± 3.54 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
df['Roi'] = df['Faturamento'] / df['Custo'] - 1

490 µs ± 4.83 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

总结:.apply + lambda 需要 721 µs 而 Pandas 内置需要 490 µs 对于 .

的小数据集快 1.47 倍

测试 2。大型 df 有 40000 行

df2 = pd.concat([df] * 10000, ignore_index=True)
%%timeit
df2['Roi'] = df2.apply(lambda x: (x['Faturamento']-x['Custo'])/x['Custo'], axis=1)

639 ms ± 3.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
df2['Roi'] = df2['Faturamento'] / df2['Custo'] - 1

767 µs ± 12.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

总结:.apply + lambda 需要 639 ms (= 639,000 µs) 而 Pandas 内置需要 767 µs :对于 .

的大型数据集,快 833 倍