axis示意图
axis=0为垂直轴,列方向操作
axis=1为水平轴,行方向操作
代码案例:
import pandas as pd
import numpy as np
fruit = pd.DataFrame(np.random.randn(5,5),columns=['a','b','c','d','e'],index=['apple','banana','pear','watermelon','plum'])
fruit
Out[4]:
a b c d e
apple 0.263318 -0.142616 1.700764 -0.989924 0.358090
banana 0.174014 -0.032459 1.139559 0.472635 -0.696391
pear -0.040526 1.825527 -0.011210 0.150228 0.049517
watermelon -2.324992 1.163329 0.948518 -1.597433 -0.080771
plum -1.203765 -1.083691 -0.425632 0.435009 -0.749044
# 第0轴 列方向汇总合计
fruit.sum(axis=0)
Out[5]:
a -3.131951
b 1.730090
c 3.351999
d -1.529485
e -1.118600
dtype: float64
#第1轴 行方向汇总合计
fruit.sum(axis=1)
Out[6]:
apple 1.189632
banana 1.057358
pear 1.973536
watermelon -1.891350
plum -3.027123
dtype: float64
#第1轴方向 行方向
fruit.drop('a',axis=1)
Out[7]:
b c d e
apple -0.142616 1.700764 -0.989924 0.358090
banana -0.032459 1.139559 0.472635 -0.696391
pear 1.825527 -0.011210 0.150228 0.049517
watermelon 1.163329 0.948518 -1.597433 -0.080771
plum -1.083691 -0.425632 0.435009 -0.749044
#第0轴方向 列方向
fruit.drop('apple',axis=0)
Out[8]:
a b c d e
banana 0.174014 -0.032459 1.139559 0.472635 -0.696391
pear -0.040526 1.825527 -0.011210 0.150228 0.049517
watermelon -2.324992 1.163329 0.948518 -1.597433 -0.080771
plum -1.203765 -1.083691 -0.425632 0.435009 -0.749044