Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert element into list of Pandas Dataframe

Have a following DataFrame:

df = pd.DataFrame({"booking": ['A', 'B', 'C'],
                   "route": [['1','2','3'],['5','4','1'],['3','6','8']]})
  1. need to insert into each "route" cell the ‘0’ at the beginning of list to get this:
df1 = pd.DataFrame({"booking": ['A', 'B', 'C'],
                    "route": [['0','1','2','3'],['0','5','4','1'],['0','3','6','8']]})
  1. and next step is to split route by legs, to get this:
df1 = pd.DataFrame({"booking": ['A', 'B', 'C'],
                    "legs": [['0>1','1>2','2>3'],['0>5', '5>4','4>1'],['0>3','3>6','6>8']]})

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use list comprehensions:

df1 = df.assign(route=[[0]+l for l in df['route']])

Output:

  booking         route
0       A  [0, 1, 2, 3]
1       B  [0, 5, 4, 1]
2       C  [0, 3, 6, 8]

Then:

df1 = df.assign(route=[[f'{a}>{b}' for a,b in zip(l, l[1:])]
                       for l in df1['route']])

Output:

  booking            route
0       A  [0>1, 1>2, 2>3]
1       B  [0>5, 5>4, 4>1]
2       C  [0>3, 3>6, 6>8]

Of course, as commented by @Nick, you can use a single step if the intermediate is not needed:

df1 = df.assign(route=[[f'{a}>{b}' for a,b in zip([0] + l, l)]
                       for l in df['route']])

Output:

  booking            route
0       A  [0>1, 1>2, 2>3]
1       B  [0>5, 5>4, 4>1]
2       C  [0>3, 3>6, 6>8]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading