简体   繁体   中英

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.

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

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. 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'] = None
df['name'] = df.apply(get_names, axis = 1)

If you face any issue/error please send screenshots.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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