簡體   English   中英

如何在 pandas 數據框中創建新列

[英]How to create a new column in a pandas data frame

我正在嘗試通過將另一個名為“Regions”的列中的值分組來創建一個名為“Continent”的新列。 我設法做的唯一代碼是這些:

my_data.loc[(my_data ["Region"] == ("Australia and New Zealand")), "Continent"] = "Australia"

但是當一個大陸有多個區域時,我會遇到麻煩。 我已經這樣做了:

my_data.loc[((my_data ["Region"] == ("Central and Eastern Europe")) & (my_data["Region"] == ("Western Europe"))), "Continent"] = "Europe"

my_data.loc[((my_data ["Region"] == ("Eastern Asia")) & (my_data["Region"] == ("Southeastern Asia"))), "Continent"] = "Asia" & (my_data["Region"] == ("Southern Asia "))), "Continent"] = "Asia"

似乎它無法識別代碼,因為當我執行此代碼時,它只是在列中出現“NaN”,而不是大陸的名稱。

有誰知道問題是什么?

這是邏輯問題,永遠不會發生一種情況AND另一種情況,因為測試一列。

所以需要| 對於按位OR

my_data.loc[((my_data ["Region"] ==  ("Central and Eastern Europe")) | (my_data["Region"] == ("Western Europe"))), "Continent"] = "Europe"

Series.isin的測試相同:

my_data.loc[my_data ["Region"].isin(["Central and Eastern Europe", "Western Europe"]), "Continent"] = "Europe"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM