首页 > 解决方案 > Numpy vs Pandas 轴

问题描述

为什么 Numpy 与 Pandas 的轴不同?

例子:

如果我想摆脱 Pandas 中的列,我可以这样做:

df.drop("column", axis = 1, inplace = True)

在这里,我们使用 axis = 1 来删除一列(在 DF 中垂直)。

在 Numpy 中,如果我想对矩阵 A 垂直求和,我会使用:

A.sum(axis = 0)

这里我使用axis = 0。

标签: pandasnumpyaxis

解决方案


axis中不经常使用pandas。数据框有 2 个维度,它们的处理方式通常截然不同。在drop轴定义中有据可查,并且实际上对应于numpy用法。

制作一个简单的数组和数据框:

In [180]: x = np.arange(9).reshape(3,3)                                         
In [181]: df = pd.DataFrame(x)                                                  
In [182]: df                                                                    
Out[182]: 
   0  1  2
0  0  1  2
1  3  4  5
2  6  7  8

从数组中删除一行或一列:

In [183]: np.delete(x, 1, 0)                                                    
Out[183]: 
array([[0, 1, 2],
       [6, 7, 8]])
In [184]: np.delete(x, 1, 1)                                                    
Out[184]: 
array([[0, 2],
       [3, 5],
       [6, 8]])

Drop 对同一个轴做同样的事情:

In [185]: df.drop(1, axis=0)                                                    
Out[185]: 
   0  1  2
0  0  1  2
2  6  7  8
In [186]: df.drop(1, axis=1)                                                    
Out[186]: 
   0  2
0  0  2
1  3  5
2  6  8

总之,定义也是一样的:

In [188]: x.sum(axis=0)                                                         
Out[188]: array([ 9, 12, 15])
In [189]: df.sum(axis=0)                                                        
Out[189]: 
0     9
1    12
2    15
dtype: int64
In [190]: x.sum(axis=1)                                                         
Out[190]: array([ 3, 12, 21])
In [191]: df.sum(axis=1)                                                        
Out[191]: 
0     3
1    12
2    21
dtype: int64

pandas 的总和是Series,它们是一维数组的 pandas 等价物。

可视化axis减少操作sum的作用有点棘手——尤其是二维数组。轴是保留还是移除?考虑一维数组的轴(删除唯一的轴)或 3d 数组(其中一个轴被删除留下两个轴)可能会有所帮助。


推荐阅读