【问题标题】:Replace one category of a categorical variable based on other categorical variable根据其他分类变量替换一个分类变量的类别
【发布时间】:2019-08-30 06:14:22
【问题描述】:

我想知道如何用基于另一个分类变量的一些值替换一个变量的一个类别。

我正在处理一个数据集。它有许多列中的 2 列。一个是 x = ['0','1','2','3+'],另一个是 - Propert_Area = ['Urban','Semiurban','Rural']。

我想根据属性区域的位置将 '3+' 替换为值 '3'、'4' 和 '5'。所以如果property_area是'Urban','3+'应该替换成'3',如果property_area是'Semiurban','3+'应该替换成'4'等等。

【问题讨论】:

    标签: python pandas replace


    【解决方案1】:

    最简单的方法是

    # df is the dataframe 
    # x and prop_area are columns 
    
    # iterate over the column
    for index, row in df.iterrows():
       if ( df.at[index,'prop_area'] =='Urban'):
          df.at[index,'x'] = '3'
       elif ( df.at[index,'prop_area'] =='Semiurban'):
          df.at[index,'x'] = '4'
       elif ( df.at[index,'prop_area'] =='Someothertype'):
          df.at[index,'x'] = '5'
       else:
           continue
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多