Kil*_*ail 23 python machine-learning scipy pandas scikit-learn
我用过了
sklearn.preprocessing.OneHotEncoder
Run Code Online (Sandbox Code Playgroud)
转换一些数据输出是scipy.sparse.csr.csr_matrix
如何将其与其他列合并回原始数据框?
我试着用pd.concat
但是得到了
TypeError: cannot concatenate a non-NDFrame object
Run Code Online (Sandbox Code Playgroud)
谢谢
Ste*_*fan 35
如果A是csr_matrix
,你可以使用.toarray()
(也.todense()
有产生a numpy
matrix
,也适用于DataFrame
构造函数):
df = pd.DataFrame(A.toarray())
Run Code Online (Sandbox Code Playgroud)
然后你可以使用它pd.concat()
.
A = csr_matrix([[1, 0, 2], [0, 3, 0]])
(0, 0) 1
(0, 2) 2
(1, 1) 3
<class 'scipy.sparse.csr.csr_matrix'>
pd.DataFrame(A.todense())
0 1 2
0 1 0 2
1 0 3 0
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 3 columns):
0 2 non-null int64
1 2 non-null int64
2 2 non-null int64
Run Code Online (Sandbox Code Playgroud)
在0.20版本中,pandas
引入了稀疏数据结构,包括SparseDataFrame
.
或者,您可以传递稀疏矩阵,sklearn
以避免在转换回时耗尽内存pandas
.只需将其他数据转换为稀疏格式,方法是numpy
array
将其传递给scipy.sparse.csr_matrix
构造函数并用于scipy.sparse.hstack
组合(请参阅文档).
每大熊猫稀疏数据结构的文档,SparseDataFrame
并且SparseSeries
已被删除。
pd.SparseDataFrame({"A": [0, 1]})
Run Code Online (Sandbox Code Playgroud)
pd.DataFrame({"A": pd.arrays.SparseArray([0, 1])})
Run Code Online (Sandbox Code Playgroud)
csr_matrix
from scipy.sparse import csr_matrix
matrix = csr_matrix((3, 4), dtype=np.int8)
df = pd.SparseDataFrame(matrix, columns=['A', 'B', 'C'])
Run Code Online (Sandbox Code Playgroud)
from scipy.sparse import csr_matrix
import numpy as np
import pandas as pd
matrix = csr_matrix((3, 4), dtype=np.int8)
df = pd.DataFrame.sparse.from_spmatrix(matrix, columns=['A', 'B', 'C', 'D'])
df.dtypes
Run Code Online (Sandbox Code Playgroud)
输出:
A Sparse[int8, 0]
B Sparse[int8, 0]
C Sparse[int8, 0]
D Sparse[int8, 0]
dtype: object
Run Code Online (Sandbox Code Playgroud)
df.sparse.to_dense()
Run Code Online (Sandbox Code Playgroud)
输出:
A B C D
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
df.sparse.density
Run Code Online (Sandbox Code Playgroud)
输出:
0.0
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25045 次 |
最近记录: |