基于其他分类变量替换分类变量的一个类别b

2024-10-03 21:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在使用数据集。它在许多列中有两列。一个是x=['0'、'1'、'2'、'3+'],另一个是-propertu Area=['Urban'、'semirban'、'Rural']

我想根据属性区域所在的位置,用值“3”、“4”和“5”替换“3+”。因此,如果物业面积为“市区”,则“3+”应替换为“3”,如果物业面积为“半市区”,则“3+”应替换为“4”,依此类推


Tags: 数据区域属性分类areaurban面积用值
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:25

最简单的方法是

# 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


相关问题 更多 >