python - 如何从熊猫的列中仅过滤掉浮点数据类型
问题描述
我有一个看起来像这样的列:
col1
20.5
21.2
21.2
17315/06/2021 09:06:481032.14310134.91082996.3001047998.93380132341231
0060232346956263174
$365140110030
$36516011007C27
$3651501100E743
我希望只有浮点值会保留在我尝试过各种替换方法的列中,但没有运气:
df['col1'] = df['col1'].replace(r'/ [ ^\d.] / g', '', regex=True, inplace=False)
似乎它什么也没做
或者
df['Temp'] = df['Temp'].replace(r'/ [ ^\d.] / g', '', regex=True, inplace=True)
将所有值作为NaN
解决方案
一个选项可能是在所有列的元素中查找所有“数字点数字”序列,如果恰好有一个匹配项,则转换为数字:
import pandas as pd
df = pd.DataFrame({"col1": [
20.5,
21.2,
21.2,
"17315/06/2021 09:06:481032.14310134.91082996.3001047998.93380132341231",
"0060232346956263174",
"$365140110030",
"$36516011007C27",
"$3651501100E743",
"This is a cell with a float 5.4",
-50.0 ]})
# with an apply/lambda
# df['floats'] = df['col1'].astype(str).str.findall("\-?\d+\.\d+").apply(lambda x: pd.to_numeric(*x) if len(x)==1 else None)
# you can also avoid the apply/lambda with a temporary series:
s = df['col1'].astype(str).str.findall("\-?\d+\.\d+")
df['floats'] = pd.to_numeric(s[s.str.len() == 1].str[0])
print(df['floats'])
0 20.5
1 21.2
2 21.2
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 5.4
9 -50.0
Name: floats, dtype: float64
推荐阅读
- azure - 使用 OAuth2 从 Azure 数据工厂向 Azure DevOps 发出 REST API 请求
- git - 将分支合并到目录 GIT
- python - 如何使用 Weatherbit API 从 Python 中解析 JSON 数据
- sql-server - SQL Server 舍入差异
- python - 错误:在 Python 中绘制热图 - 类型错误
- flopy - 如何在 FloPy Modflow6 中输出所有时间步的 MAW 头值?
- node.js - 有没有办法显示在 Node-cron 下安排的所有作业?
- unity3d - Unity中的图像动画问题
- git - 当我转到“Got to Files”时,我的 github 存储库中的某些文件未列出
- python - 如何使用下拉更新绘图标题?