There is a df column that has strings (with extra spaces) and NaNs.
I want to remove the extra spaces from the strings and keep the NaNs where they are.
I used the following code but it is giving a syntax error:
a = pd.DataFrame({'col':[np.nan, np.nan,'Java', np.nan,'Java']})
a['col2'] = [i.strip() for i in a.loc[:,'col'] if isinstance(i, str) else i]
a
## The error I'm getting on using else
#> a['col2'] = [i.strip() for i in a.loc[:,'col'] if isinstance(i, str) else i]
#> SyntaxError: invalid syntax ^
## Removing "else i" prevents the error, but then does not include the NaNs
in the result which gives the following error:
#> ValueError: Length of values (2) does not match length of index (5)
Question
- Including 'else ' in list comprehension works normally. Why is it not working in this case?
- Is there another way to strip a column of extra spaces?
question from:
https://stackoverflow.com/questions/66055907/python-list-comprehension-with-if-else-on-column-list-containing-nans 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…