python - 剥离对象系列而不删除系列中的 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
解决方案
最简单的方法是用原始值替换缺失值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
推荐阅读
- react-native - 当我们过度解雇时如何保存文本输入值?
- javascript - 量角器:e2e:我有一个测试用例,我需要在其中测试该文本是否存在
- css - CSS 背景渐变动态动画
- swift - 无法理解 Apple Watch 并发症的生命周期并让它更新
- python - python - 如何在python中使用MTCNN从文件夹中的图像中提取人脸?
- uart - 如何使用 Atmega8 做硬件 UART
- mysql - 如何使用环境变量通过一个 docker-compose.yml 部署多个数据库?
- angular - 当名称更改每次构建时,Angular pm2 如何加载 outpudHashed main.8646asdasdas6d8468.js 文件?
- kubernetes - Kubernetes 的工作节点上没有临时存储资源
- python - 一个文件中的字典或数据框未从另一个文件更新