3 python arrays numpy matrix pandas
我找到了这篇之前的帖子,它让我很接近。 如何将pandas-dataframe-subset-of-columns-and-rows-convert-a-pandas-dataframe-subset-of-columns-and-rows-to-a-numpy-array
但是,不是基于第三个中的值制作两列的单个数组(或矩阵),我需要遍历数据框并从“b”到“j”列为每个创建一个 3x3 数组(或矩阵)正确匹配“a”中的值。
dft = pd.DataFrame({'a' : ['NW' ,'NW', 'SL', 'T'],
'b' : [1,2,3,4],
'c' : [5,6,7,8],
'd' : [11,12,13,14],
'e' : [9,10,11,12],
'f' : [4,3,2,1],
'g' : [15,14,13,12],
'h' : [13,14,15,16],
'i' : [5,4,3,2],
'j' : [9,8,7,6]
})
print(dft)
a b c d e f g h i j
0 NW 1 5 11 9 4 15 13 5 9
1 NW 2 6 12 10 3 14 14 4 8
2 SL 3 7 13 11 2 13 15 3 7
3 T 4 8 14 12 1 12 16 2 6
Run Code Online (Sandbox Code Playgroud)
我想要的是 2 个单独的数组,每个数组 1 个 NW
[[ 1 5 11]
[ 9 4 15]
[13 5 9]]
[[ 2 6 12]
[10 3 14]
[14 4 8]]
Run Code Online (Sandbox Code Playgroud)
我尝试了以下操作并收到了一个非常难看的错误。该代码是基于原始帖子的尝试。
dft.loc[dft['a'] == 'NW',['b', 'c', 'd'], ['e', 'f', 'g'], ['h', 'i', 'j']].values
Run Code Online (Sandbox Code Playgroud)
这是错误 -
IndexingError Traceback(最近一次调用最后一次) in () ----> 1 dft.loc[dft['a'] == 'NW',['b', 'c', 'd'], ['e ', 'f', 'g'], ['h', 'i', 'j']].values
D:\Applications\Anaconda\lib\site-packages\pandas\core\indexing.py in getitem (self, key) 1323 除了 (KeyError, IndexError): 1324 pass -> 1325 return self._getitem_tuple(key) 1326 else:第 1327 章
D:\Applications\Anaconda\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup) 839 840 # 没有多索引,所以验证所有的索引器 --> 841 self._has_valid_tuple(tup ) 842 843 # GH #836 的丑陋黑客
D:\Applications\Anaconda\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key) 186 for i, k in enumerate(key): 187 if i >= self.obj.ndim: - -> 188 raise IndexingError('Too many indexers') 189 if not self._has_valid_type(k, i): 190 raise ValueError("基于位置的索引只能有 [%s]"
索引错误:索引器太多
想法?我那么近,却又那么遥远。
你可以在没有循环的情况下做到这一点
a = df.loc[df['a'] == 'NW', 'b':'j']
n = a.shape[0]
new_a = a.values.reshape(n,3,3)
Run Code Online (Sandbox Code Playgroud)
你得到
array([[[ 1, 5, 11],
[ 9, 4, 15],
[13, 5, 9]],
[[ 2, 6, 12],
[10, 3, 14],
[14, 4, 8]]])
Run Code Online (Sandbox Code Playgroud)