Skip to content
Advertisement

Python: how to delete space in column of lists?

I have a dataframe like this:

    lokalnyid               1_5000_pi025
0   255EE55D-0418-4FF7-E053-CC2BA8C0BA5E    ['73221_902271_M-34-57-A-a-3-4.tif']
1   255EE55D-0473-4FF7-E053-CC2BA8C0BA5E    ['73221_902617_M-34-57-A-c-1-2.tif']
2   255EE55D-04AC-4FF7-E053-CC2BA8C0BA5E    ['73221_902644_M-34-57-A-c-1-4.tif', ' 73221_902642_M-34-57-A-c-3-2.tif']
3   255EE55D-0552-4FF7-E053-CC2BA8C0BA5E    ['73221_902617_M-34-57-A-c-1-2.tif']
4   255EE55D-0A84-4FF7-E053-CC2BA8C0BA5E    ['73221_902392_M-34-56-B-d-4-4.tif', ' 73221_902643_M-34-57-A-c-3-3.tif']
5   255EE55D-0BCA-4FF7-E053-CC2BA8C0BA5E    ['73221_902271_M-34-57-A-a-3-4.tif']
6   255EE55D-0BED-4FF7-E053-CC2BA8C0BA5E    ['73221_902645_M-34-57-A-c-2-1.tif']
7   255EE55D-0C24-4FF7-E053-CC2BA8C0BA5E    ['73221_902142_M-34-57-A-a-4-4.tif', ' 73221_902268_M-34-57-A-a-4-3.tif']

Some records in the column ‘1_5000_pi025’ has the space between ‘ and number, for example:

['73221_902644_M-34-57-A-c-1-4.tif', ' 73221_902642_M-34-57-A-c-3-2.tif']

Space between ‘ and 73221_902642_M-34-57-A-c-3-2.tif. I was trying few solution but didn’t work. How can I delete space from every record in the column ‘1_5000_pi025’?

Didn’t work:

1 . df['1_5000_pi025'] = df['1_5000_pi025'].str.strip()

2 . df_all_quality_roofs['1_5000_pi025'] = [x.replace(' ', '') for x in df_all_quality_roofs['1_5000_pi025']]

Error: ‘AttributeError: ‘list’ object has no attribute ‘replace’

Advertisement

Answer

.str doesn’t work because it contains a list. Try:

df['1_5000_pi025'] = df['1_5000_pi025'].map(lambda r: list(map(str.strip, r)))
Advertisement