它集列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
但是我覺得這裏更好的使用map
如果只male
和female
值需要轉換爲一些其他值:
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
[**此答案可能有幫助**](https://stackoverflow.com/a/44891687/2336654) – piRSquared