Python .loc 混乱

Python .loc confusion

我正在使用 Datacamp 平台为泰坦尼克号做一个 Kaggle 教程。

我了解在 Pandas 中使用 .loc - 使用列标签按行 select 值...

我的困惑来自于在 Datacamp 教程中,我们想要在 "Sex" 列中找到所有 "Male" 输入,并将其替换为值 0。他们使用以下一段代码可以做到:

titanic.loc[titanic["Sex"] == "male", "Sex"] = 0

有人可以解释一下这是如何工作的吗?我以为 .loc 接受了行和列的输入,那么 == 是做什么用的?

不应该是:

titanic.loc["male", "Sex"] = 0

谢谢!

如果条件仅为 True,则将列 Sex 设置为 1,其他值保持不变:

titanic["Sex"] == "male"

样本:

titanic = pd.DataFrame({'Sex':['male','female', 'male']})
print (titanic)
      Sex
0    male
1  female
2    male

print (titanic["Sex"] == "male")
0     True
1    False
2     True
Name: Sex, dtype: bool

titanic.loc[titanic["Sex"] == "male", "Sex"] = 0
print (titanic)

0       0
1  female
2       0

它与 boolean indexing with loc 非常相似 - 它 select 只有 Sex 列的值按条件:

print (titanic.loc[titanic["Sex"] == "male", "Sex"])
0    male
2    male
Name: Sex, dtype: object

但我认为这里最好使用 map 如果只有 malefemale 值需要转换为其他值:

titanic = pd.DataFrame({'Sex':['male','female', 'male']})
titanic["Sex"] = titanic["Sex"].map({'male':0, 'female':1})
print (titanic)
   Sex
0    0
1    1
2    0

编辑:

主要loc用于按索引和列设置新值:

titanic = pd.DataFrame({'Sex':['male','female', 'male']}, index=['a','b','c'])
print (titanic)
      Sex
a    male
b  female
c    male

titanic.loc["a", "Sex"] = 0
print (titanic)
      Sex
a       0
b  female
c    male

titanic.loc[["a", "b"], "Sex"] = 0
print (titanic)
    Sex
a     0
b     0
c  male