简体   繁体   English

如何在 Pandas 中创建一个新列并根据现有列中的条件值向该新列添加值?

[英]How to create a new column in pandas and add value to that new column based on the conditional value from the existing column?

So, I have got a data-frame with a-lot of encodings.所以,我有一个带有很多编码的数据帧。 I want to create a new column where I want to add string values based on the numbers from the first column of the dataset.我想创建一个新列,我想根据数据集第一列中的数字添加字符串值。 For example if the first column in the dataset has numbers 0,1,2,3 and 4 then I want to add string 'Thor' in the same rows in the new column.例如,如果数据集中的第一列有数字 0、1、2、3 和 4,那么我想在新列的相同行中添加字符串“Thor”。

Any help would be appreciated.任何帮助,将不胜感激。 Thank you谢谢

So far I have tried:到目前为止,我已经尝试过:

def name_values(data):
    if(data['facefeat_1']==-0.141472) | (data['facefeat_1']== -0.141472) | (data['facefeat_1']== -0.221594) | (data['facefeat_1']== -0.181907) | (data['facefeat_1']== -0.184878):
        data['Name'] = 'Thor'

facefeat_1 being the name of the first column in dataframe and 'Name' being the new column I want to populate facefeat_1 是数据框中第一列的名称,'Name' 是我要填充的新列

The desired output should be所需的输出应该是

Name Thor Loki名字托尔·洛基

What I got: None None我得到了什么:无 无

Screenshot:截屏: 在此处输入图片说明

另一个截图

Assuming that you have a dataframe (df) which has a column facefeat_1, and based on the values of facefeat_1 column of a particular row you want the df.name value to be a string.假设您有一个包含 facefeat_1 列的数据框 (df),并且基于特定行的 facefeat_1 列的值,您希望 df.name 值是一个字符串。 You can add a apply function in the following manner您可以通过以下方式添加应用功能

def get_names(row):
    if row['facefeat_1'] in [-0.141472,-0.141472, -0.141472, -0.221594,-0.181907,-0.184878]:
        return "Thor"
    elif row['facefeat_1'] in some_list:
        return "Loki"
    else:
        return "Odin"

and then you can set df['name'] in the following manner然后您可以按以下方式设置 df['name']

df['name'] = None
df['name'] = df.apply(get_names, axis = 1)

If you face any issue/error please send screenshots.如果您遇到任何问题/错误,请发送屏幕截图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM