我想知道如何将一个类别的变量替换为基于另一个类别变量的一些值。
我正在处理一个数据集。它有许多列中的2列。一个是x= '0','1','2','3+‘,另一个是- Propert_Area =’城市‘,’半城市‘,’农村‘。
我想根据属性区域所在的位置将'3+‘替换为值'3’、‘4’和'5‘。因此,如果property_area是“城市”,“3+”应该替换为“3”,如果property_area是“半城市”,“3+”应该替换为“4”,以此类推。
发布于 2019-08-28 06:50:03
最简单的方法是
# 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:
continuehttps://stackoverflow.com/questions/57683042
复制相似问题