首页 > 解决方案 > 剥离对象系列而不删除系列中的 int/float 单元格

问题描述

我有一系列类型object,当使用Series.str.strip()只包含的单元格时,int会变成Nan.

我该如何避免这种情况?


例子

sr = pd.Series([1,2,3,'foo   '])
sr.str.strip()

0    NaN
1    NaN
2    NaN
3    foo
dtype: object

期望的结果

0    1
1    2
2    3
3    foo
dtype: object

标签: pythonpandasnanseriesstrip

解决方案


最简单的方法是用原始值替换缺失值Series.fillna

sr = pd.Series([1,2,3,'foo   '])

sr.str.strip().fillna(sr)

或仅对通过以下测试的字符串进行条带化isinstance

print (sr.apply(lambda x: x.strip() if isinstance(x, str) else x))

0      1
1      2
2      3
3    foo
dtype: object

推荐阅读