how to reverse order of links in python jupyter notebook for each column

Viewed 56

Hi i have a dataframe and i wish to reverse the url links in each column where the last become the first

before
 
www.a.com, www.b.com, www.c.com, www.d.com, www.e.com

becomes

www.e.com, www.d.com, www.c.com, www.b.com, www.a.com

I have tried this code but it doesn't work as the commas have some problem, is there another way to solve it?

I have attached the error photos here: enter image description here

df['Image URLs']=df.URL.str.split().apply(lambda x: ' '.join(x[::-1]))

the dataframe is like this enter image description here

1 Answers

Assuming that your dataframe has the following structure:

[{"urls":"www.a.com,www.b.com"},{"urls":"www.c.com,www.d.com,www.e.com"}]

this will reverse the url order in each cell:

df["urls"].apply(lambda x: ",".join(x.split(",")[::-1]))

The logic is the following:

  • We first use apply to execute a function to every cell of the column.
  • We split the string value inside the cell to create a list of urls.
  • We reverse that list (using [::-1])
  • We join the elements of that list into a string with commas in between.
Related