numpy和pandas axis的差异

本文介绍了NumPy中数组元素求和的方法及其参数说明,并通过实例演示了不同轴方向上的求和操作。同时,文章还讲解了Pandas DataFrame中的sum方法使用方式,包括忽略缺失值进行求和及按行或按列求和的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.numpy

numpy.sum(aaxis=Nonedtype=Noneout=Nonekeepdims=<class 'numpy._globals._NoValue'>)[source]

Sum of array elements over a given axis.

 

Parameters:

a : array_like

Elements to sum.

axis : None or int or tuple of ints, optional

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

New in version 1.7.0.

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

 

arr = np.random.randn(5,4)#正态分布数据
print(arr)
print(arr.sum()) # 数组/矩阵中所有元素求和,等价于np.sum(arr)
print(np.sum(arr, axis=0))# 按列去求和; 
print(arr.sum(axis=1))  # 按行去求和;
[[ 0.04154798  0.25697028  2.36239272 -1.72886735]
 [ 0.50448843 -0.63285194  2.9090727   0.61004107]
 [ 0.10730241 -0.13162546 -0.67925053  0.12864452]
 [ 0.04125252 -0.03968486 -0.60453958  0.94637586]
 [ 1.65060502 -0.18266035 -1.06259085  0.18515147]]
4.681774035077944
[ 2.34519635 -0.72985234  2.92508445  0.14134557]
[ 0.93204362  3.39075026 -0.57492907  0.34340393  0.59050528]
2.pandas 

DataFrame.sum(axis=Noneskipna=Nonelevel=Nonenumeric_only=Nonemin_count=0**kwargs)[source]
axis 
{index (0), columns (1)}
d
f
one    two
a    1.40    NaN
b    7.10    -4.5
c    NaN    NaN
d    0.75    -1.3
 
 

df.sum(axis=1)

a    1.40
b    2.60
c    0.00
d   -0.55
dtype: float64

 



pandas.DataFrame.dropna(axis=0how='any'thresh=Nonesubset=Noneinplace=False)[source]

axis : {0 or ‘index’, 1 or ‘columns’}, default 0

 
 

Determine if rows or columns which contain missing values are removed.

  • 0, or ‘index’ : Drop rows which contain missing values.
  • 1, or ‘columns’ : Drop columns which contain missing value.

Deprecated since version 0.23.0:: Pass tuple or list to drop on multiple

axes.

 
 

how : {‘any’, ‘all’}, default ‘any’


 
df
 iddatecitycategoryageprice
one10012013-01-02Beijing100-A231200.0
two10022013-01-03NaN100-B44NaN
three10032013-01-04guangzhou110-A542133.0
four10042013-01-05Shenzhen110-C325433.0
five10052013-01-06shanghai210-A34NaN
six10062013-01-07BEIJING130-F324432.0

 

 

 

 

 

 

 

df.dropna(axis=1)#针对列向有nan值的情况
 iddatecategoryage
one10012013-01-02100-A23
two10022013-01-03100-B44
three10032013-01-04110-A54
four10042013-01-05110-C32
five10052013-01-06210-A34
six10062013-01-07130-F32

转载于:https://www.cnblogs.com/yitiaodahe/p/9264892.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值