pandas - Numpy vs Pandas 轴
问题描述
为什么 Numpy 与 Pandas 的轴不同?
例子:
如果我想摆脱 Pandas 中的列,我可以这样做:
df.drop("column", axis = 1, inplace = True)
在这里,我们使用 axis = 1 来删除一列(在 DF 中垂直)。
在 Numpy 中,如果我想对矩阵 A 垂直求和,我会使用:
A.sum(axis = 0)
这里我使用axis = 0。
解决方案
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 数组(其中一个轴被删除留下两个轴)可能会有所帮助。
推荐阅读
- javascript - 如何修复[对象,对象]
- continuous-integration - 本地计算机上的 Go Server 服务启动然后停止
- python - Azure 和签名密钥问题。适用于治疗但不完全适用于python
- php - 如何使用上传器工厂在 magento 2 中上传自定义图像?
- python-3.x - 创建新的自定义字段类型 Odoo
- ios - 尝试在桥接头文件中添加我的帮助程序类时出现错误
- c - libmodbus 函数输出的部分输出打印
- swift - 在 Xcode 中使用干净的 swift 架构的注册页面出现问题
- java - Firebase 作业调度程序无法在 Oreo 设备上工作
- python - Django - 尝试加载该表单时,CustomModelForm 中的“extra_fields”在模型内联界面中给出“无法查找”错误