0

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"
4
  • why are you changing field in the last three elif, but a in the first? A typo? Commented Sep 30, 2015 at 16:09
  • 1
    For starters if you just did this df3.loc[df['field']=='a','field'] = '111' and so on you wouldn't need to iterate at all just call loc like above 4 times Commented Sep 30, 2015 at 16:12
  • It would be helpful if you provide the example of the data frame you start with and the data frame that you want to end with Commented Sep 30, 2015 at 17:09
  • Anand, thank you for pointing out the typo, i have modified my post. Commented Sep 30, 2015 at 17:23

2 Answers 2

1

You can simply do:

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

and so on...

Sign up to request clarification or add additional context in comments.

Comments

0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.