我正在使用Datacamp平台为泰坦尼克号做一个Kaggle教程。
我理解在Pandas中使用.loc - 使用列标签按行选择值...
我的困惑来自以下事实:在Datacamp教程中,我们想要在“Sex”列中找到所有“Male”输入,并将其替换为值0.他们使用以下代码来完成它:
titanic.loc[titanic["Sex"] == "male", "Sex"] = 0
有人可以解释一下这是如何运作的吗?我以为.loc接受了行和列的输入,那么== for?
是什么不应该是:
titanic.loc["male", "Sex"] = 0
谢谢!
答案 0 :(得分:4)
如果条件仅为Sex
,则将列1
设置为True
,其他值不受影响:
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
与loc
非常相似 - 它只按条件选择列Sex
的值:
print (titanic.loc[titanic["Sex"] == "male", "Sex"])
0 male
2 male
Name: Sex, dtype: object
但如果只有male
和female
值需要转换为其他值,我认为更好的是使用map
:
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