python-将 pandas 矩阵转换为DataFrame [英] python - Converting pandas Matrix to DataFrame
本文介绍了python-将 pandas 矩阵转换为DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个矩阵:
items = [0, 1, 2, 3]
item_to_item = pd.DataFrame(index=items, columns=items)
我已经在其中添加了值,
I've put values in it so:
- 其对称性
- 对角线全为0
例如:
0 1 2 3
0 0 4 5 9
1 4 0 3 7
2 5 3 0 3
3 9 7 3 0
我想创建一个所有可能对的数据帧(从[0,1,2,3]开始),这样就不会有成对的(x, x)
,如果(x, y)
在其中,我就不希望(y, x)
因为它的对称性并保持相同的值.
最后,我将获得以下数据框(或numpy 2d数组)
I want to create a data frame of all possible pairs (from [0, 1, 2, 3]) so that there wont be pairs of (x, x)
and if (x, y)
is in, I dont want (y, x)
becuase its symetric and holds the same value.
In the end I will have the following Dataframe (or numpy 2d array)
item, item, value
0 1 4
0 2 5
0 3 9
1 2 3
1 3 7
2 3 3
推荐答案
Here's a NumPy solution with np.triu_indices
-
In [453]: item_to_item
Out[453]:
0 1 2 3
0 0 4 5 9
1 4 0 3 7
2 5 3 0 3
3 9 7 3 0
In [454]: r,c = np.triu_indices(len(items),1)
In [455]: pd.DataFrame(np.column_stack((r,c, item_to_item.values[r,c])))
Out[455]:
0 1 2
0 0 1 4
1 0 2 5
2 0 3 9
3 1 2 3
4 1 3 7
5 2 3 3
这篇关于python-将 pandas 矩阵转换为DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文