1

When I was first starting out with Python, the below code was acceptable to me, because it got the job done. But currently re-writing and cleaning up this code for future use--is there a better way to make this more Pythonic via a loop or function?

movements['Agency.1_2'] = movements['Agency.1'] + ' to ' + movements['Agency.2']
movements['Agency.2_3'] = movements['Agency.2'] + ' to ' + movements['Agency.3']
movements['Agency.3_4'] = movements['Agency.3'] + ' to ' + movements['Agency.4']
movements['Agency.4_5'] = movements['Agency.4'] + ' to ' + movements['Agency.5']
movements['Agency.5_6'] = movements['Agency.5'] + ' to ' + movements['Agency.6']
movements['Agency.6_7'] = movements['Agency.6'] + ' to ' + movements['Agency.7']
movements['Agency.7_8'] = movements['Agency.7'] + ' to ' + movements['Agency.8']
movements['Agency.8_9'] = movements['Agency.8'] + ' to ' + movements['Agency.9']
movements['Agency.9_10'] = movements['Agency.9'] + ' to ' + movements['Agency.10']

Ultimately, this code spits out a bunch of new columns with concatenated strings with a ' to ' in the middle, e.g:

+-------+------------+------------+
|  id   | Agency.1_2 | Agency.2_3 | 
+-------+------------+------------+
|   1   |   a to b   |   b to c   | 
|   2   |   b to d   |   f to g   | 
|   3   |   z to y   |            | 
+-------+------------+------------+

The current code works, so nbd if there isn't a better way. But would love to learn how to do this so I can push myself. Thanks!

1 Answer 1

2
for i in range(10):
    movements[f"Agency.{i}_{i+1}"] = f"{movements[f'Agency.{i}']} to {movements[f'Agency.{i+1}']}"
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! This got me within range of a code that worked! for i in range(10): a[f"Agency.{i+1}_{i+2}"] = a[f"Agency.{i+1}"] + ' to ' + a[f"Agency.{i+2}"]
@ColinSorensen I'm glad! Could you tell me why what I used didn't work so I can try to improve it?
It was creating some strange string values in the cells without any "to"...e.g. this is copy/pasted: ''0 foo\n1 bar\n2 baz\n3."
Ah! I was missing the final curly brace! You can use which ever you like, but mine should work now.

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.