Python .loc非自愿更改多个列
我有一个df,看起来像这样:Python .loc非自愿更改多个列,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个df,看起来像这样: Location Field Value Count 01 Ethnicity minority 124 02 Gender male 96 03 Religion minority 115 04 Gender female 132 我正在使用.loc将Value中的值更改为0,1而不是文本。当我使
Location Field Value Count
01 Ethnicity minority 124
02 Gender male 96
03 Religion minority 115
04 Gender female 132
我正在使用.loc
将Value
中的值更改为0,1而不是文本。当我使用df.loc[df['Value']='male']=0
值
改变,但字段
也改变。我如何避免这种情况发生
此外,此DF是直接从CSV文件创建的,这是我所做的第一次更改,因此我不会将函数堆叠在彼此之上。您需要指定列:
df.loc[df['Value'] == 'male', 'Value'] = 0
print(df)
Location Field Value Count
0 1 Ethnicity minority 124
1 2 Gender 0 96
2 3 Religion minority 115
3 4 Gender female 132
或者使用np.where进行所有转换:
df['Value'] = np.where(df['Value'].eq('male'), 0, 1)
print(df)
Location Field Value Count
0 1 Ethnicity 1 124
1 2 Gender 0 96
2 3 Religion 1 115
3 4 Gender 1 132
您需要指定列:
df.loc[df['Value'] == 'male', 'Value'] = 0
print(df)
Location Field Value Count
0 1 Ethnicity minority 124
1 2 Gender 0 96
2 3 Religion minority 115
3 4 Gender female 132
或者使用np.where进行所有转换:
df['Value'] = np.where(df['Value'].eq('male'), 0, 1)
print(df)
Location Field Value Count
0 1 Ethnicity 1 124
1 2 Gender 0 96
2 3 Religion 1 115
3 4 Gender 1 132
您还可以使用
pandas.DataFrame.replace
df.replace({'Value':{'male':0,'male':1})
这将返回一个带有替换值的新数据帧
Location Field Value Count
0 1 Ethnicity minority 124
1 2 Gender 0 96
2 3 Religion minority 115
3 4 Gender 1 132
您还可以使用
pandas.DataFrame.replace
df.replace({'Value':{'male':0,'male':1})
这将返回一个带有替换值的新数据帧
Location Field Value Count
0 1 Ethnicity minority 124
1 2 Gender 0 96
2 3 Religion minority 115
3 4 Gender 1 132
您的
np.where
语句将Value
的所有行变为1。df.loc[df['Value']='male','Value']=0
有效。是的,这就是我使用np.where定义它的方式。如果df['Value']等于男性,则将df['Value']设置为0,否则将其设置为0。这就像excel.yournp中的IF语句一样。其中语句将Value
的所有行变为1。df.loc[df['Value']='male','Value']=0
有效。是的,这就是我使用np.where定义它的方式。如果df['Value']等于男性,则将df['Value']设置为0,否则将其设置为0。就像excel中的IF语句一样。