[英]Convert sparse matrix to pandas dataframe
import numpy as np
from scipy.sparse import csr_matrix
csr = csr_matrix(np.array(
[[0, 0, 4],
[1, 0, 0],
[2, 0, 0],]))
# Return a Coordinate (coo) representation of the csr matrix.
coo = csr.tocoo(copy=False)
# Access `row`, `col` and `data` properties of coo matrix.
df = pd.DataFrame({'index': coo.row, 'col': coo.col, 'data': coo.data})[['index', 'col', 'data']]
>>> df.head()
index col data
0 0 2 4
1 1 0 1
2 2 0 2
我嘗試將 scipy csr_matrix 矩陣轉換為 dataframe,其中列代表矩陣的索引、列和數據。
唯一的問題是我上面嘗試的內容不會為值為 0 的列生成行。這是我希望 output 看起來像的樣子:
>>> df.head()
index col data
0 0 0 0
1 0 1 0
2 0 2 4
3 1 0 1
4 1 1 0
5 1 2 0
6 2 0 2
7 2 1 0
8 2 2 0
您會看到上面的代碼片段取自此線程中的此答案。
我的請求/問題:有沒有辦法將矩陣轉換為 df 並且還包括值為 0 的矩陣元素?
一種方法是創建一個filling
DataFrame 並將它(使用combine_first
)與您已有的組合:
df = pd.DataFrame({'index': coo.row, 'col': coo.col, 'data': coo.data}).set_index(["index", "col"])
n_rows, n_cols = coo.shape
rows, cols = map(np.ndarray.flatten, np.mgrid[:n_rows, :n_cols])
filling = pd.DataFrame({"index": rows, "col": cols, "data": np.repeat(0, n_rows * n_cols)}) \
.set_index(["index", "col"])
res = df.combine_first(filling).reset_index()
print(res)
輸出
index col data
0 0 0 0.0
1 0 1 0.0
2 0 2 4.0
3 1 0 1.0
4 1 1 0.0
5 1 2 0.0
6 2 0 2.0
7 2 1 0.0
8 2 2 0.0
melt
為“長”格式df = your_sparse_matrix_data.todense()
(pd.DataFrame(df)
.melt()
.reset_index()
.rename(columns = {'index':'row','variable':'column'}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.