python稀疏矩阵scipy.sparse中的csr_matrix及astype('category')

本文详细介绍使用Python的Pandas库进行数据编码和标签映射的方法,以及如何利用Scipy的CSR矩阵进行高效的数据存储与索引。通过具体实例展示了Pandas在数据处理中的灵活性,及CSR矩阵在稀疏数据存储方面的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、python astype(‘category’), 编码和标签对应,categories 和 code 映射为字典

import pandas as pd
 
# 创建数据集
df = pd.DataFrame.from_dict(
            {
            'col1': ['A', 'B', 'C', 'B', 'A', 'D'],
            'col2': ['aa', 'bb', 'bb', 'aa', 'dd', 'dd'],
            'col3': ['yes', 'yes','no','no','yes','yes']
            }
            ,orient='columns')
# df 
#   col1 col2 col3
# 0    A   aa  yes
# 1    B   bb  yes
# 2    C   bb   no
# 3    B   aa   no
# 4    A   dd  yes
# 5    D   dd  yes
 
# 转换为分类数据
df = df.astype('category') # 可以指定特定的列转为分类数据 df['col1'] = df['col1'].astype('category')
 
# 将标签数据转换为编码
df_code = pd.DataFrame({col: df[col].cat.codes for col in df}, index=df.index)
 
# df_code 
#    col1  col2  col3
# 0     0     0     1
# 1     1     1     1
# 2     2     1     0
# 3     1     0     0
# 4     0     2     1
# 5     3     2     1
 
# 将编码和标签一一对应,转为字典,方便查询
df_code_dict = {col: {code: category for code, category in enumerate(df[col].cat.categories)} for col in df}
# df_code_dict 
# {'col1': {0: 'A', 1: 'B', 2: 'C', 3: 'D'},
#  'col2': {0: 'aa', 1: 'bb', 2: 'dd'},
#  'col3': {0: 'no', 1: 'yes'}}

2.1、csr_matrix索引方式1

这种方式百度介绍的较多
indptr = np.array([0, 2, 3, 6])
indices = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()

输出:
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])
csr中的r表示row,即为行优先。

indptr中的元素两个两个的看,前两个为0和2,表示第一行有2-0=2个元素,再在indices中选前两个元素,得到在列上的位置为0和2,填充data的元素为1和2。接在是indptr中的2和3,所以第二行有3-2=1个元素,要填充的列位置是indices 中的2,元素从data中找为3. 在接下来是indptr中的3和6,表示第三行有6-3=3个元素,要填充的位置是indices 中的0、1、2,元素从data中找为4,5,6.

2.1、csr_matrix索引方式2

根据矩阵值进行索引

df = pd.DataFrame.from_dict(
            {
            'col1': [1, 0, 2, 3, 2, 1],
            'col2': [1, 0, 1, 2, 3, 4],
            'col3': [14, 15, 10, 20, 30, 40]
            }
            ,orient='columns')
df

在这里插入图片描述

sparse_item_user = sparse.csr_matrix((df['col3'], (df['col1'], df['col2'])))
sparse_item_user.toarray()

在这里插入图片描述

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[5], line 5 3 import numpy as np 4 import matplotlib.pyplot as plt ----> 5 from scipy.spatial.distance import cdist 6 print(f"numpy: {np.__version__}, matplotlib: {plt.matplotlib.__version__}") 7 except ImportError as e: File D:\miniconda\lib\site-packages\scipy\spatial\__init__.py:110 1 """ 2 ============================================================= 3 Spatial algorithms and data structures (:mod:`scipy.spatial`) (...) 107 QhullError 108 """ # noqa: E501 --> 110 from ._kdtree import * 111 from ._ckdtree import * # type: ignore[import-not-found] 112 from ._qhull import * File D:\miniconda\lib\site-packages\scipy\spatial\_kdtree.py:4 1 # Copyright Anne M. Archibald 2008 2 # Released under the scipy license 3 import numpy as np ----> 4 from ._ckdtree import cKDTree, cKDTreeNode # type: ignore[import-not-found] 6 __all__ = ['minkowski_distance_p', 'minkowski_distance', 7 'distance_matrix', 8 'Rectangle', 'KDTree'] 11 def minkowski_distance_p(x, y, p=2): File _ckdtree.pyx:11, in init scipy.spatial._ckdtree() File D:\miniconda\lib\site-packages\scipy\sparse\__init__.py:300 294 # Original code by Travis Oliphant. 295 # Modified and extended by Ed Schofield, Robert Cimrman, 296 # Nathan Bell, and Jake Vanderplas. 298 import warnings as _warnings --> 300 from ._base import * 301 from ._csr import * 302 from ._csc import * File D:\miniconda\lib\site-packages\scipy\sparse\_base.py:5 1 """Base class for sparse matrices""" 3 import numpy as np ----> 5 from ._sputils import (asmatrix, check_reshape_kwargs, check_shape, 6 get_sum_dtype, isdense, isscalarlike, 7 matrix, validateaxis, getdtype) 9 from ._matrix import spmatrix 11 __all__ = ['isspmatrix', 'issparse', 'sparray', 12 'SparseWarning', 'SparseEfficiencyWarning'] File D:\miniconda\lib\site-packages\scipy\sparse\_sputils.py:10 8 from math import prod 9 import scipy.sparse as sp ---> 10 from scipy._lib._util import np_long, np_ulong 13 __all__ = ['upcast', 'getdtype', 'getdata', 'isscalarlike', 'isintlike', 14 'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype', 15 'broadcast_shapes'] 17 supported_dtypes = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, 18 np.uintc, np_long, np_ulong, np.longlong, np.ulonglong, 19 np.float32, np.float64, np.longdouble, 20 np.complex64, np.complex128, np.clongdouble] File D:\miniconda\lib\site-packages\scipy\_lib\_util.py:13 10 from typing import TypeAlias, TypeVar 12 import numpy as np ---> 13 from scipy._lib._array_api import array_namespace, is_numpy, xp_size 14 from scipy._lib._docscrape import FunctionDoc, Parameter 17 AxisError: type[Exception] File D:\miniconda\lib\site-packages\scipy\_lib\_array_api.py:18 15 import numpy.typing as npt 17 from scipy._lib import array_api_compat ---> 18 from scipy._lib.array_api_compat import ( 19 is_array_api_obj, 20 size as xp_size, 21 numpy as np_compat, 22 device as xp_device, 23 is_numpy_namespace as is_numpy, 24 is_cupy_namespace as is_cupy, 25 is_torch_namespace as is_torch, 26 is_jax_namespace as is_jax, 27 is_array_api_strict_namespace as is_array_api_strict 28 ) 30 __all__ = [ 31 '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal', 32 'get_xp_devices', (...) 38 'xp_take_along_axis', 'xp_unsupported_param_msg', 'xp_vector_norm', 39 ] 42 # To enable array API and strict array-like input validation File D:\miniconda\lib\site-packages\scipy\_lib\array_api_compat\numpy\__init__.py:1 ----> 1 from numpy import * # noqa: F403 3 # from numpy import * doesn't overwrite these builtin names 4 from numpy import abs, max, min, round # noqa: F401 File D:\miniconda\lib\site-packages\numpy\testing\__init__.py:11 8 from unittest import TestCase 10 from . import _private ---> 11 from ._private.utils import * 12 from ._private.utils import (_assert_valid_refcount, _gen_alignment_data) 13 from ._private import extbuild File D:\miniconda\lib\site-packages\numpy\testing\_private\utils.py:469 465 pprint.pprint(desired, msg) 466 raise AssertionError(msg.getvalue()) --> 469 @np._no_nep50_warning() 470 def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True): 471 """ 472 Raises an AssertionError if two items are not equal up to desired 473 precision. (...) 537 538 """ 539 __tracebackhide__ = True # Hide traceback for py.test File D:\miniconda\lib\site-packages\numpy\__init__.py:414, in __getattr__(attr) 410 raise AttributeError(__former_attrs__[attr], name=None) 412 if attr in __expired_attributes__: 413 raise AttributeError( --> 414 f"`np.{attr}` was removed in the NumPy 2.0 release. " 415 f"{__expired_attributes__[attr]}", 416 name=None 417 ) 419 if attr == "chararray": 420 warnings.warn( 421 "`np.chararray` is deprecated and will be removed from " 422 "the main namespace in the future. Use an array with a string " 423 "or bytes dtype instead.", DeprecationWarning, stacklevel=2) AttributeError: module 'numpy' has no attribute '_no_nep50_warning'
最新发布
07-24
<think>我们遇到了一个错误:AttributeError: module 'numpy' has no attribute '_no_nep50_warning' 这个错误通常是由于NumPy版本不兼容导致的。在NumPy 2.0中,移除了`_no_nep50_warning`这个内部函数。 而scipy的测试模块(numpy.testing)中使用了这个函数,因此当scipy与较新的numpy版本(如2.0)一起使用时,可能会出现此问题。 解决方案: 1. 降级NumPy版本:由于scipy可能还没有完全兼容numpy 2.0,我们可以降级到numpy 1.x版本。 例如:`pip install numpy==1.26.4` 2. 升级SciPy版本:如果存在支持numpy 2.0的scipy版本,可以尝试升级scipy。 例如:`pip install --upgrade scipy` 3. 如果上述方法都不行,可以尝试重新安装scipy,因为有时候安装过程中可能出现问题。 在Jupyter中,我们可以通过以下步骤操作: 步骤1:检查当前安装的numpy和scipy版本 ```python import numpy as np import scipy print("NumPy version:", np.__version__) print("SciPy version:", scipy.__version__) ``` 步骤2:根据版本决定操作 - 如果numpy版本是2.x,而scipy版本较旧(比如低于1.13.0,但实际上需要查看scipy的更新日志以确认何时支持numpy2.0),则降级numpy或升级scipy。 步骤3:执行安装命令(在Jupyter中可以使用!) - 降级numpy示例: ```python !pip install numpy==1.26.4 ``` - 升级scipy示例: ```python !pip install --upgrade scipy ``` 步骤4:重启内核 安装完成后,需要重启Jupyter内核以使更改生效。 注意:如果使用conda环境,建议使用conda命令进行安装,以避免环境混乱。 另外,如果问题仍然存在,可以考虑检查环境是否冲突,或者尝试创建一个新的虚拟环境。 由于错误发生在导入scipy.spatial.distance.cdist时,所以确保scipy和numpy版本兼容至关重要。 下面是一个快速修复的代码示例(在Jupyter中运行):</think>### 解决NumPy兼容性错误 您在导入`scipy.spatial.distance.cdist`时遇到的`AttributeError: module 'numpy' has no attribute '_no_nep50_warning'`错误,通常是由于NumPy与SciPy版本不兼容导致的。以下是完整的解决方案: **问题原因分析**: 1. NumPy 2.0+ 移除了`_no_nep50_warning`属性 2. 旧版SciPy尝试访问此已移除的属性 3. 常见于NumPy 2.x + SciPy <1.13的组合 **解决方案步骤**: 1. **检查当前版本**(在Jupyter新单元运行): ```python !python -c "import numpy as np; import scipy; print(f'numpy=={np.__version__}\nscipy=={scipy.__version__}')" ``` 2. **降级NumPy(推荐方案)**: ```bash # 在Jupyter单元中运行 !pip install "numpy<2.0" --force-reinstall ``` 3. **升级SciPy(替代方案)**: ```bash # 在Jupyter单元中运行 !pip install --upgrade "scipy>=1.13" ``` 4. **重启内核**: - 顶部菜单 → Kernel → Restart Kernel - 或快捷键:`0 0`(按两次零) 5. **验证修复**: ```python # 在新单元测试式导入 import numpy as np from scipy.spatial.distance import cdist print("导入成功!") ``` **预防措施**: ```bash # 创建专用环境(在终端执行) conda create -n cs231n python=3.10 conda activate cs231n pip install numpy==1.26.4 scipy==1.11.4 jupyter matplotlib ``` > **注意**:如果使用conda,优先使用`conda install`而非pip,避免依赖冲突。若问题持续,尝试`pip install --no-cache-dir`清除安装缓存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值