Krisjay
Krisjay

Reputation: 127

Python Pandas - Multiple assignment

Is there an efficient way to make the following assignment without using for loops?

for i in range(0,len(df3)):
    if df3.loc[i,'field'] == "a":
        df3.loc[i,'field'] = "111"
    elif df3.loc[i, 'field'] == "b":
        df3.loc[i, 'field'] = "222"
    elif df3.loc[i, 'field'] == "c":
        df3.loc[i, 'field'] = "333"
    else:
        df3.loc[i,'field'] = "444"

Upvotes: 0

Views: 89

Answers (2)

rocconnick
rocconnick

Reputation: 86

You can simply do:

 df3.loc[df.field == 'a', 'field'] = '111'

and so on...

Upvotes: 1

Prune
Prune

Reputation: 77857

You can shorten the code, but you still need a loop to hop through the df3 structure and hit all your "field" fields.

xlate = {'a':'111', 'b':'222', 'c':'333'}
for i in range(len(df3)):
    df3.loc[i, 'field'] = xlate.get(df3.loc[i, 'field'], '444')

Upvotes: 0

Related Questions