根据其他类别变量替换类别变量的一个类别

时间:2019-08-27 22:41:48

标签: python pandas replace

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

我正在使用数据集。它有2列。一个是x = ['0','1','2','3+'],另一个是-Propert_Area = ['Urban','Semiurban','Rural']。

我想根据属性区域所在的事实用值“ 3”,“ 4”和“ 5”替换“ 3+”。因此,如果property_area是“城市”,则应将“ 3+”替换为“ 3”,如果property_area是“ Semiurban”,则将“ 3+”替换为“ 4”,依此类推。

1 个答案:

答案 0 :(得分:0)

最简单的方法是

# 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