Pandas:如何编写一个更快的循环来检查一列,然后根据第一列的值更改另一列的符号?
我的数据框中有大约 1000 万行数据。下面是 2 行的示例。
| 指数 | 数量 | 借记卡信用卡 |
|---|---|---|
| 0 | 1000 | 1 |
| 1 | 2000年 | 2 |
回答
你可以用.loc,但没有循环:
df.loc[df['debit/credit'].eq(2), 'Amount'] *= -1
输出:
Amount debit/credit
0 1000 1
1 -2000 2
或者
通过np.where():
import numpy as np
df['Amount'] = np.where(df['debit/credit'].eq(2), df['Amount']*-1, df['Amount'])
性能测试:
让我们创建一个包含 2 列和 1000 万行的示例数据框:
import time
df = pd.DataFrame({'Amount': np.random.randint(1000, 10000, size=10000000),
'debit/credit': np.random.randint(1, size=10000000) + 1})
1)循环:
start = time.perf_counter()
change_credits_to_negative(df)
stop = time.perf_counter()
print(stop - start)
97.34215749999998
2)位置:
start = time.perf_counter()
df.loc[df['debit/credit'].eq(2), 'Amount'] *= -1
stop = time.perf_counter()
print(stop - start)
0.03006110000001172
它给了我们 97 秒。与循环和 0.03 秒。没有它。
THE END
二维码