Python - 在包含 NaN 的列/列表上使用 if-else 进行列表理解
Python - List comprehension with if-else on column / list containing NaNs
有一个包含字符串(带有额外空格)和 NaN 的 df 列。
我想从字符串中删除多余的空格并将 NaN 保留在原处。
我使用了以下代码,但它给出了语法错误:
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)
问题
- 在列表理解中包含 'else ' 可以正常工作。为什么在这种情况下它不起作用?
- 是否有其他方法去除一列多余的空格?
顺序有误。尝试
a['col2'] = [i.strip() if isinstance(i, str) else i for i in a.loc[:,'col']]
如果没有 else,在理解的末尾放置一个 if 语句就可以了。如果两者都有,则需要放在前面。令人困惑?是的,总是让我绊倒。
else
的位置不正确,整个 if/else 都在 for
之前。这是一个工作示例:
a = pd.DataFrame({'col':[np.nan, np.nan,'Java', np.nan,'Java']})
a['col2'] = [i.strip() if isinstance(i, str) else i for i in a.loc[:,'col']]
有一个包含字符串(带有额外空格)和 NaN 的 df 列。
我想从字符串中删除多余的空格并将 NaN 保留在原处。
我使用了以下代码,但它给出了语法错误:
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)
问题
- 在列表理解中包含 'else ' 可以正常工作。为什么在这种情况下它不起作用?
- 是否有其他方法去除一列多余的空格?
顺序有误。尝试
a['col2'] = [i.strip() if isinstance(i, str) else i for i in a.loc[:,'col']]
如果没有 else,在理解的末尾放置一个 if 语句就可以了。如果两者都有,则需要放在前面。令人困惑?是的,总是让我绊倒。
else
的位置不正确,整个 if/else 都在 for
之前。这是一个工作示例:
a = pd.DataFrame({'col':[np.nan, np.nan,'Java', np.nan,'Java']})
a['col2'] = [i.strip() if isinstance(i, str) else i for i in a.loc[:,'col']]