pandas - Python SparseArray Dtype 到浮点数
问题描述
熊猫:1.1.2
如何将 sparsearray dtype 转换为 float64 dtype?
df
id N_ERVisits N_admission N_diagnoses N_hospDays N_procedures
0 1 0.0 0.0 0.000090 0.0 0.000000
1 1 0.0 0.0 0.000000 0.0 0.000000
2 1 0.0 0.0 0.000000 0.0 0.000000
3 1 0.0 0.0 0.000800 0.0 0.000000
4 1 0.0 0.0 0.000000 0.0 0.000000
df.dtypes
id int64
N_ERVisits Sparse[float64, 0]
N_admission Sparse[float64, 0]
N_diagnoses Sparse[float64, 0]
N_hospDays Sparse[float64, 0]
N_procedures Sparse[float64, 0]
dtype: object
我以为我可以进行标准转换:
df['N_ERVisits'] = df['N_ERVisits'].astype('float64')
df.dtypes
empi int64
N_ERVisits Sparse[float64, 0.0]
N_admission Sparse[float64, 0]
N_diagnoses Sparse[float64, 0]
N_hospDays Sparse[float64, 0]
N_procedures Sparse[float64, 0]
dtype: object
解决方案
如果您不再需要稀疏性,请使用SparseArray.values.to_dense()
将系列转换为密集的 numpy 数组。然后该.astype()
功能按预期工作。
import pandas as pd
import numpy as np
# data
arr = np.zeros((100,))
arr[1] = 1
arr[10] = 10
df = pd.DataFrame(data={
'id': np.array(range(1, 101)),
'col1': pd.arrays.SparseArray(arr, fill_value=0)
})
# df["col1"].values.dtype == Sparse[float64, 0]
# sparsity retained (note the difference in fill_value)
df["col2"] = df["col1"].astype(pd.SparseDtype(np.float64))
df["col3"] = df["col1"].astype(np.float64)
# no sparsity
df["col4"] = df["col1"].values.to_dense().astype(np.float64)
print(df.dtypes)
输出:
id int64
col1 Sparse[float64, 0]
col2 Sparse[float64, nan]
col3 Sparse[float64, 0.0]
col4 float64
dtype: object
看似棘手的现象可以通过列的底层对象类型来理解。必须.values
显式调用才能在底层SparseArray
本身上工作。
type(df["col1"])
Out[5]: pandas.core.series.Series
type(df["col1"].values)
Out[6]: pandas.core.arrays.sparse.array.SparseArray
注意我的熊猫版本是 1.0.3,但行为应该是相同的。
推荐阅读
- java - 使用Java将返回值放入参数中
- flutter - 如何在颤动中为一个小部件应用两个补间?
- algorithm - 通过索引和元素删除快速查找的数据结构
- swift - 在整个窗口上显示新的 NSView 后,如何停止访问窗口中的所有 NSView?
- python-3.x - 最高 bin 的直方图边界
- x11 - X 会话响应鼠标事件,但不显示光标
- javascript - 如何在 R Shiny 中为 DT 使用 localStorage 选项?
- java - 在前缀 url 中查找最大匹配
- windows - Shellcode 中的弹出窗口
- node.js - OpenAPI & ExpressJS - 只打印第一个属性作为响应