Jacky
Jacky

Reputation: 750

How to iterate through two pandas columns and create a new column

I am trying to create a new column by concatenating two columns with certain conditions.

master['work_action'] = np.nan
for a,b in zip(master['repair_location'],master['work_service']):
    if a == 'Field':
        master['work_action'].append(a + " " + b)
    elif a == 'Depot':
        master['work_action'].append(a + " " + b)
    else:
        master['work_action'].append(a)

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

The problem is with master['work_action'].append(a + " " + b)

If I change my code to this:

test = []
for a,b in zip(master['repair_location'],master['work_service']):
    if a == 'Field':
        test.append(a + " " + b)
    elif a == 'Depot':
        test.append(a + " " + b)
    else:
        test.append(a)

I get exactly what I want in a list. But I want it in a pandas column. How do I create a new pandas column with the conditions above?

Upvotes: 1

Views: 1158

Answers (2)

Luis Fernando Cantu
Luis Fernando Cantu

Reputation: 78

If performance is important, I would use numpy's select:

master = pd.DataFrame(
    {
        'repair_location': ['Field', 'Depot', 'Other'],
        'work_service':[1, 2, 3]
    }
)

master['work_action'] = np.select(
    condlist= [
        master['repair_location'] == 'Field',
        master['repair_location'] == 'Depot'
    ],
    choicelist= [
        master['repair_location'] + ' ' + master['work_service'].astype(str),
        master['repair_location'] + ' ' + master['work_service'].astype(str)
    ],
    default= master['repair_location']
)

Which results in:

  repair_location  work_service work_action
0           Field             1     Field 1
1           Depot             2     Depot 2
2           Other             3       Other

Upvotes: 2

jcaliz
jcaliz

Reputation: 4021

Append method is for insert values at the end. You are trying to concatenate two strings values. Use apply method:

def fun(a,b):
    if a == 'Field':
        return a + " " + b
    elif a == 'Depot':
        return a + " " + b
    else:
       return a

master['work_action'] = master.apply(lambda x: fun(x['repair_location'], x['work_service']), axis=1)

Upvotes: -1

Related Questions