How to iterate over pandas dataframe and create new column

后端 未结 3 521
执笔经年
执笔经年 2021-01-01 07:15

I have a pandas dataframe that has 2 columns. I want to loop through it\'s rows and based on a string from column 2 I would like to add a string in a newly created 3th colum

3条回答
  •  太阳男子
    2021-01-01 07:52

    You can also try this (if you want to keep the for loop you use) :

    new_column = []
    
    for i in df.index:
        if df.ix[i]['Column2']==variable1:
            new_column.append(variable2)
        elif df.ix[i]['Column2']==variable3:
            new_column.append(variable4)
        else : #if both conditions not verified
            new_column.append(other_variable)
    
    df['Column3'] = new_column
    

提交回复
热议问题