【发布时间】:2022-01-10 18:19:50
【问题描述】:
考虑循环遍历我的 DataFrame:
import pandas as pd
df = pd.DataFrame({
'Price': [1000, 1000, 1000, 2000, 2000, 2000, 2000, 1400, 1400],
'Count': [0, 0, 0, 0, 0, 0, 0, 0, 0]
})
for idx in df.index:
if df['Price'].iloc[idx] > 1500:
if idx > 0:
df['Count'].iloc[idx] = df['Count'].iloc[idx - 1] + 1
导致:
| Price | Count | |
|---|---|---|
| 0 | 1000 | 0 |
| 1 | 1000 | 0 |
| 2 | 1000 | 0 |
| 3 | 2000 | 1 |
| 4 | 2000 | 2 |
| 5 | 2000 | 3 |
| 6 | 2000 | 4 |
| 7 | 1400 | 0 |
| 8 | 1400 | 0 |
有没有更有效的方法来做到这一点?
【问题讨论】:
标签: python pandas dataframe loops vectorization