Read image path from pandas data frame and arrange them based on filename

Viewed 317

I have a data frame with the image paths in first column. As shown here: input dataframe

The filename of imagecontains IDs(ImageID) and type of image (Topo). I want to generate output data frame such as, it generates different columns of different Topos. So for one Image ID I get six columns of Topos. Output as shown here: Output dataframe

The number of Topos can be different, it can run from 4 to 27. So the numbers of output columns can be different.

1 Answers

First we have to extract the list of Topos:

list_of_topos = list(pd.DataFrame([x.split('_')[-1].split('.')[0] for x in df['Image ID'].tolist()])[0].unique())

Here we created a series of values after splitting the Image ID by "_" and ".", and take a list of unique values

Then we create the new columns as follow:

df[list_of_topos] = None

The final step is to assign the values for each row columns:

for index, row in df.iterrows():
    extention = "." + row['Image'].split(".")[-1]
    row[list_of_topos] = ["_".join(row['Image'].split("_")[:-1]) + x + extention for x in list_of_topos]

Please note that this solution is supposing that all data is in the same structure as in your question

Related