【发布时间】:2021-05-24 10:35:26
【问题描述】:
我有一个如下所示的 DataFrame:
| Id | Price |
|---|---|
| 1 | 300 |
| 1 | 300 |
| 1 | 300 |
| 2 | 400 |
| 2 | 400 |
| 3 | 100 |
我的目标是将每个观察的价格除以具有相同 ID 号的行数。预期的输出是:
| Id | Price |
|---|---|
| 1 | 100 |
| 1 | 100 |
| 1 | 100 |
| 2 | 200 |
| 2 | 200 |
| 3 | 100 |
但是,我在寻找执行此操作的最优化方法时遇到了一些问题。我确实使用下面的代码做到了这一点,但是运行需要超过 5 分钟(因为我有大约 20 万次观察):
# For each row in the dataset, get the number of rows with the same Id and store them in a list
sum_of_each_id=[]
for i in df['Id'].to_numpy():
sum_of_each_id.append(len(df[df['Id']==i]))
# Creating an auxiliar column in the dataframe, with the number of rows associated to each Id
df['auxiliar']=sum_of_each_id
# Dividing the price by the number of rows with the same Id
df['Price']=df['Price']/df['auxiliar']
请告诉我最好的方法是什么?
【问题讨论】: