下面是我生成一个数据框架的代码:
import pandas as pd
import numpy as np
dff = pd.DataFrame(np.random.randn(1,2),columns=list('AB'))
然后我得到了数据框架:
+------------+---------+--------+
| | A | B |
+------------+---------+---------
| 0 | 0.626386| 1.52325|
+------------+---------+--------+
当我输入命令时:
dff.mean(axis=1)
我得到:
0 1.074821
dtype: float64
根据pandas的参考,axis=1代表列,我希望命令的结果是
A 0.626386
B 1.523255
dtype: float64
我的问题是:轴在熊猫中是什么意思?
我认为,正确答案应该是“这很复杂”。
“轴”这个词本身在不同的人心中会产生不同的形象
假设y轴,它应该是一个垂直的图像。但是,现在考虑一条垂直线x=0。这也是一条垂直线,但是x轴上的值为0。
类似地,当我们说axis='index'(意思是axis=0)时,我们说的是索引所在的“垂直”方向吗?或者由索引值处理的一系列数据?熊猫往往意味着第一个意思,垂直方向。
熊猫本身也不是100%一致的,看看下面的例子,它们几乎有相同的共同主题:
# [1] piling dfs
pd.concat([df0, df1], axis='index')
# adding dfs on top of each other vertically like pilling up a column,
# but, we will use the word 'index'
# [2] for every column in df: operate on it
df.apply(foo, axis='index')
df.mean('A', axis='index')
a_boolean_df.all(axis='index')
# apply an operation to a vertical slice of data, ie. a column,
# then apply the same operation to the next column on the right
# then to the right again... until the last column
# but, we will use the word 'index'
# [3] delete a column or row of data
df.drop(axis='index', ...)
df.dropna(axis='index', ...)
# this time, we are droping an index/row, a horizontal slice of data.
# so OBVIOUSLY we will use the word 'index'
# [4] drop duplicate
df.drop_duplicates(subset=['mycolumn0', 'mycolumn1']...)
# thank God we don't need to deal with the "axis" bs in this
我认为还有另一种理解方式。
对于np。数组,如果我们想要消除列,我们使用axis = 1;如果我们想消除行,我们使用axis = 0。
np.mean(np.array(np.ones(shape=(3,5,10))),axis = 0).shape # (5,10)
np.mean(np.array(np.ones(shape=(3,5,10))),axis = 1).shape # (3,10)
np.mean(np.array(np.ones(shape=(3,5,10))),axis = (0,1)).shape # (10,)
对于pandas对象,axis = 0表示按行操作,axis = 1表示按列操作。这与numpy的定义不同,我们可以检查numpy.doc和pandas.doc的定义