開始使用免費開始

同時取代多個值 I

在這個練習中,你會運用 .replace() 函式,把多個值一次取代為一個或多個指定的值。你會再次使用 names 資料集,這個資料集包含美國按年份、性別與 Ethnicity 分類的熱門姓名等資訊。

你的目標是把所有被標記為黑裔或白裔且非西語裔的 Ethnicity,統一改成 non-hispanic。請記住,資料集中這些 Ethnicity 的標記為:['BLACK NON HISP', 'BLACK NON HISPANIC', 'WHITE NON HISP' , 'WHITE NON HISPANIC'],都應該被取代為 'NON HISPANIC'。

本練習屬於課程

使用 pandas 撰寫高效程式碼

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

start_time = time.time()

# Replace all non-Hispanic ethnicities with 'NON HISPANIC'
names['Ethnicity'].____[(names["Ethnicity"] == ____) | 
                      (____["Ethnicity"] == ____) | 
                      (____[____] == ____) | 
                      (____[____] == ____)] = ____

print("Time using .loc[]: sec".format(time.time() - start_time))
編輯並執行程式碼