Ell*_*ner 4 python arrays numpy
我有几个2D numpy数组(矩阵),每个我想将它转换为包含数组值的向量和包含每个行/列索引的向量.
例如,我可能有这样的数组:
x = np.array([[3, 1, 4],
[1, 5, 9],
[2, 6, 5]])
Run Code Online (Sandbox Code Playgroud)
我基本上想要这些价值观
[3, 1, 4, 1, 5, 9, 2, 6, 5]
Run Code Online (Sandbox Code Playgroud)
和他们的立场
[[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]
Run Code Online (Sandbox Code Playgroud)
我的最终目标是将这些放入pandas DataFrame中,如下所示:
V | x | y
--+---+---
3 | 0 | 0
1 | 0 | 1
4 | 0 | 2
1 | 1 | 0
5 | 1 | 1
9 | 1 | 2
6 | 2 | 0
5 | 2 | 1
3 | 2 | 2
Run Code Online (Sandbox Code Playgroud)
其中V是值,x是行位置(索引),y是列位置(索引).
我想我可以一起破解一些东西,但我试图找到有效的方法来做到这一点而不是摸索.例如,我知道我可以使用类似的东西来获取值x.reshape(x.size, 1),并且我可以尝试从中创建索引列x.shape,但似乎应该有更好的方法.
我不知道它是否最有效,但是numpy.meshgrid专为此而设计:
x = np.array([[3, 1, 4],
[1, 5, 9],
[2, 6, 5]])
XX,YY = np.meshgrid(np.arange(x.shape[1]),np.arange(x.shape[0]))
table = np.vstack((x.ravel(),XX.ravel(),YY.ravel())).T
print table
Run Code Online (Sandbox Code Playgroud)
这会产生:
[[3 0 0]
[1 1 0]
[4 2 0]
[1 0 1]
[5 1 1]
[9 2 1]
[2 0 2]
[6 1 2]
[5 2 2]]
Run Code Online (Sandbox Code Playgroud)
然后我认为df = pandas.DataFrame(table)会给你你想要的数据框架.
您还可以让 pandas 为您完成工作,因为您将在数据框中使用它:
x = np.array([[3, 1, 4],
[1, 5, 9],
[2, 6, 5]])
df=pd.DataFrame(x)
#unstack the y columns so that they become an index then reset the
#index so that indexes become columns.
df=df.unstack().reset_index()
df
level_0 level_1 0
0 0 0 3
1 0 1 1
2 0 2 2
3 1 0 1
4 1 1 5
5 1 2 6
6 2 0 4
7 2 1 9
8 2 2 5
#name the columns and switch the column order
df.columns=['x','y','V']
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df = df[cols]
df
V x y
0 3 0 0
1 1 0 1
2 2 0 2
3 1 1 0
4 5 1 1
5 6 1 2
6 4 2 0
7 9 2 1
8 5 2 2
Run Code Online (Sandbox Code Playgroud)