remove duplicate separator pandas

Viewed 192

I have following columns that I am reading from a excel sheet

CM              FOTO 1              FOTO 2              FOTO 3              FOTO 4           
some text some  744905_L050_01.jpg  NaN                 744905_B001_01.jpg  NaN
some text some  NaN                 NaN                 NaN                 NaN
some text some  621059_W034_01.jpg  621059_W034_02.jpg  621059_W034_03.jpg  NaN     
some text some  NaN                 NaN                 NaN                 NaN

Then I am writing a new csv file, and creating following columns:

df_["DESCRIPTION"] = df["CM "]
df_["IMAGES_URL"] = df[["FOTO 1 ", "FOTO 2 ", "FOTO 3 ", "FOTO 4 "]].apply(lambda x: x.str.cat(sep='|'), axis=1)
df_["WAREHOUSE"] = "D"

finally I am storing it in a csv file and using semicolon as separator:

df_.to_csv('path/my_file.csv', encoding = 'utf-8', index=False, sep=';')

The output looks as follows:

DESCRIPTION;IMAGES_URL;WAREHOUSE
some text some;744905_L050_01.jpg|744905_B001_01.jpg;D
some text some;;D
some text some;621059_W034_01.jpg|621059_W034_02.jpg|621059_W034_03.jpg;D
some text some;;D

However if all four Foto columns have NaN values, it writes double ;; into the csv file. How can I remove the double semicolons and replace it with only one semicolon?

1 Answers

If you artificially replace the ";;" with a ";", you will have data from, say Foto 3 getting into the Foto 2 column. Is that really what you want? If not, you can just fill the NaNs with something else with:

df_.fillna('No foto', inplace=True)
Related