【问题标题】:Change column value based on calculated mean of other column in python pandas根据python pandas中其他列的计算平均值更改列值
【发布时间】:2020-06-20 03:12:59
【问题描述】:

我是熊猫的新手。我经历了很多问题,但没有找到答案。

我有以下数据集。

Name    || Price    || Cuisine Category || City || Region || Cuisine Types || Rating Types || Rating

Pizza  || 600  || Fast Food,Pizza || Ajmer ||   Ana Saga || Quick Bites || Good || 3.9

...     ...     ...     ...     ...     ...     ...     ...     ...

Chawla's || 300 || Beverages || Ajmer || Sagar Lake     || Cafe || Average || 3.3

Masala || 0 || North,South Indian || Ajmer || Ram Ganj || Mess || None || NEW

我想改变以下的值:

  • 根据特定菜肴类型的平均评分和基于计算的评分的评分类型对新评分进行评分

  • 价格为 0,基于该特定区域的平均价格

我尝试改变价格:

读取 CSV 文件

data = pd.read_csv('/content/Ajmer.csv')

计算区域平均价格

gregion = round(data.groupby('Region')['Price'].mean()) 

试图替换价格列的0

data['Price'] = data['Price'].replace(0, gregion[data['Region']])

但我的价格栏没有改变。

我尝试更改评级:

读取 CSV 文件

data2 = pd.read_csv('/content/Ajmer.csv')

创建单独的数据框,使其不会影响平均值。

filtered_rating = data2[(data2['Rating'] == 'NEW') | (data2['Rating'] == '-') | (data2['Rating'] == 'Opening')]

从原始数据中删除2

data2.drop(data2.loc[data['Rating']=='NEW'].index, inplace=True)
data2.drop(data2.loc[data['Rating']=='-'].index, inplace=True)
data2.drop(data2.loc[data['Rating']=='Opening'].index, inplace=True)

计算美食类型的平均评分

c = round(data2.groupby('Cuisine Types')['Rating'].mean(),1)

这给了我如下输出:

Cuisine Types

Bakery            3.4

Confectionery     3.4

Dessert Parlor    3.5

...

Quick Bites       3.4

Sweet Shop        3.4

Name: Rating, dtype: float64

尝试替换值

filtered_rating['Rating'].replace('NEW', c[data2['Region']], inplace=True)
filtered_rating['Rating'].replace('-', c[data2['Region']], inplace=True)
filtered_rating['Rating'].replace('Opening', c[data2['Region']], inplace=True)

但我的评分栏没有改变。

预期输出

  • 价格列中价格为零的行的特定区域的平均价格

  • 评级列中评级为新的特定美食类型的平均评级

谁能帮我做这件事?

提前致谢! 我会很高兴得到您的帮助

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    假设您有如下数据。

    data
        name            region     price    cuisine_type          rating_type   rating
    0   pizza           NY          500      fast food              average        3.3
    1   burger          NY          350      fast food              good           4.1
    2   lobster         LA          1500     seafood                good           4.5
    3   mussels         LA          1000     seafood                average        3.9
    4   shawarma        NY          300    mediterranean            average        3.4
    5   kabab           LA          600    mediterranean            good             4
    6   pancake         NY          250      breakfast              average        3.7
    7   waffle          LA          450      breakfast              good           4.2
    8   fries           NY          0        fast food              None           NEW
    9   crab            LA          0        seafood                None        Opening
    10  tuna sandwich   NY          0        seafood                None           NEW
    11  onion rings     LA          0        fast food              None        Opening
    

    现在根据您的问题,我们需要将评级为 NEW 或 Opening 的评级替换为相应美食类型的平均评级。并在其为 0 时的价格与相应地区的平均价格。并在最后更新 None 的评分类型。

    #get a list of cuisine types
    cuisine_type_list=data.cuisine_type.unique().tolist()
    
    cuisine_type_list
    ['fast food', 'seafood', 'mediterranean', 'breakfast']
    
    #get a list of regions
    region_list=data.region.unique().tolist()
    
    region_list
    ['NY', 'LA']
    
    #replace the ratings 
    for i in cuisine_type_list:
      data.loc[(data.cuisine_type==i) & (data.rating.isin(['NEW', 'Opening'])), 'rating']=round(data.loc[(data.cuisine_type==i) & (data.rating.isin(['NEW', 'Opening'])==False)].rating.mean(), 2)
    
    #replace price when 0
    for i in region_list:
      data.loc[(data.region==i) & (data.price==0), 'price']=round(data.loc[(data.region==i) & (data.price!=0)].price.mean(), 2)
    
    
    #function to assign rating type (assuming good for rating>=4)
    def calculate_rating_type(row):
      if row['rating'] >= 4:
        return 'good'
      else: 
        return 'average'
    
    #update rating type
    data.loc[data.rating_type.isnull(), 'rating_type']=data.loc[data.rating_type.isnull()].apply(lambda row: calculate_rating_type(row), axis=1)
    

    这是更新后的数据

    data
        name            region     price    cuisine_type          rating_type   rating
    0   pizza           NY          500      fast food              average        3.3
    1   burger          NY          350      fast food              good           4.1
    2   lobster         LA          1500     seafood                good           4.5
    3   mussels         LA          1000     seafood                average        3.9
    4   shawarma        NY          300    mediterranean            average        3.4
    5   kabab           LA          600    mediterranean            good             4
    6   pancake         NY          250      breakfast              average        3.7
    7   waffle          LA          450      breakfast              good           4.2
    8   fries           NY          350      fast food              average        3.7
    9   crab            LA          887.5    seafood                good           4.2
    10  tuna sandwich   NY          350      seafood                good           4.2
    11  onion rings     LA          887.5    fast food              average        3.7
    

    【讨论】:

    • 非常感谢!这样做的绝妙方法
    【解决方案2】:

    你可以试试下面的代码:

    gregion = round(data.groupby('Region')['Price'].mean()) 
    # convert your group by to DataFrame
    gregion = pd.DataFrame(gregion)
    gregion.reset_index(inplace=True)
    
    # merge the datas and drop the new column that is created
    data = data.merge(gregion, left_on='Region', right_on='Region', suffixes=('_x', ''))
    data = data.drop(columns={'Price_x'})
    
    filtered_rating = data[(data['Rating'] == 'NEW') | (data['Rating'] == '-') | (data['Rating'] == 'Opening')]
    
    # you don't need to re-upload the file
    data2 = data.copy()
    
    data2.drop(data2.loc[data2['Rating']=='NEW'].index, inplace=True)
    data2.drop(data2.loc[data2['Rating']=='-'].index, inplace=True)
    data2.drop(data2.loc[data['Rating']=='Opening'].index, inplace=True)
    
    # do the same with c
    c = round(data2.groupby('Cuisine Types')['Rating'].mean(),1)
    c = pd.DataFrame(c)
    c.reset_index(inplace=True)
    
    filtered_rating = filtered_rating.merge(c, left_on='Cuisine Types', right_on='Cuisine Types', how='left', suffixes=('_x', ''))
    filtered_rating = filtered_rating.drop(columns={'Rating_x'})
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2022-07-28
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多