【问题标题】:How to divide a column by the number of rows with equal id in a dataframe?如何将一列除以数据框中具有相同 id 的行数?
【发布时间】: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']

请告诉我最好的方法是什么?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    试试groupbytransform

    • 使用groupby('Id')根据id创建组
    • 使用 `transform('count') 获取组中每行的值计数
    • df["Price] 除以包含计数的系列。
    df = pd.DataFrame({"Id":[1,1,1,2,2,3],"Price":[300,300,300,400,400,100]})
    
    df["new_Price"] = (df["Price"]/df.groupby("Id")["Price"].transform("count")).astype('int')
    
    print(df)
    
       Id  Price  new_Price
    0   1    300        100
    1   1    300        100
    2   1    300        100
    3   2    400        200
    4   2    400        200
    5   3    100        100
    

    【讨论】:

      【解决方案2】:
      import pandas as pd
      
      df = pd.DataFrame({"id": [1, 1, 1, 2, 2, 3], "price": [300, 300, 300, 400, 400, 100]})
      df.set_index("id") / df.groupby("id").count()
      

      解释:

      • df.groupby("id").count() 计算具有相同 ID 号的行数。生成的 DataFrame 将有一个 Id 作为索引。
      • df.set_index("id") 会将 Id 列设置为索引
      • 然后我们简单地划分帧,pandas 将通过索引匹配数字。

      【讨论】:

      • 谢谢,这是一个非常聪明和简单的方法,而且它也有效!
      猜你喜欢
      • 2019-11-26
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 2015-10-18
      • 2019-02-25
      • 2012-01-13
      相关资源
      最近更新 更多