Python Pandas - 从数据框创建用于乘法的数组或矩阵

标签 python arrays pandas numpy matrix

我找到了这篇之前的帖子,它让我很接近。 how-to-convert-a-pandas-dataframe-subset-of-columns-and-rows-into-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

我想要的是 2 个独立的数组,每个 NW 一个

     [[ 1  5 11]
      [ 9  4 15]
      [13  5  9]]

     [[ 2  6 12]
      [10  3 14]
      [14  4  8]]

我尝试了以下方法并收到了一个非常丑陋的错误。代码是在原帖基础上的一次尝试。

    dft.loc[dft['a'] == 'NW',['b', 'c', 'd'], ['e', 'f', 'g'], ['h', 'i', 'j']].values

这里是错误-

IndexingError Traceback (most recent call last) 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 except (KeyError, IndexError): 1324 pass -> 1325 return self._getitem_tuple(key) 1326 else: 1327 key = com._apply_if_callable(key, self.obj)

D:\Applications\Anaconda\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup) 839 840 # no multi-index, so validate all of the indexers --> 841 self._has_valid_tuple(tup) 842 843 # ugly hack for 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("Location based indexing can only have [%s] "

IndexingError: Too many indexer

想法?离我那么近,又那么诱人。

  • 而且我不知道如何设置错误代码的格式 - 那么有什么帮助可以清除它吗?

最佳答案

你可以不用循环就可以做到这一点

a = df.loc[df['a'] == 'NW', 'b':'j']
n = a.shape[0]
new_a = a.values.reshape(n,3,3)

你得到

array([[[ 1,  5, 11],
        [ 9,  4, 15],
        [13,  5,  9]],

       [[ 2,  6, 12],
        [10,  3, 14],
        [14,  4,  8]]])

关于Python Pandas - 从数据框创建用于乘法的数组或矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48054473/

相关文章:

php - 解析错误: syntax error, unexpected T_VARIABLE in Xro_config.php on line 21

python - Pandas : Replace NaNs with mean of 'n' nearest non-empty values in column

Pandas:插入缺失的行数据并在组内使用条件进行迭代

python - 将 pdf 转换为图像时出现类型错误 : TypeError ("object of type ' NoneType' has no len()", )

python - 如何将类添加到 LinkML 中的 SchemaDefinition?

python - 查找四个集合交集的所有线段成员(维恩图)

python - pandas.to_csv() 一些单词为粗体

ios - 如何比较 2 个数组并将最后一项附加到第二个数组 iOS Swift 3

c++ - 为什么*ptr在printf中?

python-3.x - 按行特定列表选择 Pandas 数据框列