简体   繁体   English

Python:如何从数据帧创建稀疏矩阵?

[英]Python: How to create a sparse matrix from a dataframe?

Using pandas=1.1.5.使用熊猫=1.1.5。 I just want to convert the below df into a sparse matrix.我只想将下面的 df 转换为稀疏矩阵。 Sorry if this is trivial.对不起,如果这是微不足道的。 I rarely use sparse matrix.我很少使用稀疏矩阵。 Thanks in advance!提前致谢!

df1 = pd.DataFrame({'Grp': ['3' , '10'],
                   'Rating': ['1', '2']
                   })

You can set the type of the dataframe to a SparseDtype您可以将数据帧的类型设置为SparseDtype

import pandas as pd

dtype = pd.SparseDtype(int, fill_value=0)
df1 = df1.astype(dtype)

In [15]: df1.dtypes
Out[15]: 
Grp       Sparse[int64, 0]
Rating    Sparse[int64, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM