简体   繁体   English

如何在 pandas 数据框中创建新列

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

I am trying to create a new column called "Continent" by grouping the values in another column called "Regions".我正在尝试通过将另一个名为“Regions”的列中的值分组来创建一个名为“Continent”的新列。 The only codes that I managed to do are these:我设法做的唯一代码是这些:

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

But I am having trouble when there is more than one region for a continent.但是当一个大陆有多个区域时,我会遇到麻烦。 I have done this:我已经这样做了:

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"

it seems like it does not recognize the code because when I execute this, it just appears "NaN" in the column, instead of the name of the continent.似乎它无法识别代码,因为当我执行此代码时,它只是在列中出现“NaN”,而不是大陆的名称。

Does anybody know what the problem is?有谁知道问题是什么?

Here is logic problem, never happens one condition AND another one, because test one column.这是逻辑问题,永远不会发生一种情况AND另一种情况,因为测试一列。

So need |所以需要| for bitwise OR :对于按位OR

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

What working same like test by Series.isin :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.

相关问题 如何从 pandas 数据框的列值创建新行 - How to create a new rows from column values of pandas data frame 如何从一列中提取信息以在熊猫数据框中创建新列 - How to extract information from one column to create a new column in a pandas data frame 根据现有列中的 2 个条件创建新的 pandas 数据框 - Create new pandas data frame based on 2 conditions in an existing column 使用 Pandas 从现有列创建新列到数据框 - Create a new column to data frame from existing columns using Pandas 基于现有列在 pandas 数据框中创建新列 - Create new columns in pandas data frame based on existing column 在Pandas Data-frame中使用掩码的字符串值创建一个新列 - Create a new column in Pandas Data-frame with a string value of a mask 循环熊猫列名称以创建新的数据框 - Looping Pandas Column Names To Create New Data Frame 如何通过在 pandas 数据帧中迭代来比较两个日期并创建一个新列 - how to compare two date by iterating in a pandas data frame and create a new column 如何将lambda函数应用于pandas数据框中的某些行并创建新列 - How to apply a lambda function to certain rows in a data frame in pandas and create a new column 如何在迭代pandas数据帧时创建新列并插入行值 - How to create new column and insert row values while iterating through pandas data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM