这篇主要整理pandas常用的基本函数,主要分为五部分:
常用的主要是4个:
df.describe()
#运行截图
Height Weight
count 183.000000 189.000000
mean 163.218033 55.015873
std 8.608879 12.824294
min 145.400000 34.000000
25% 157.150000 46.000000
50% 161.900000 51.000000
75% 167.500000 65.000000
max 193.900000 89.000000
在Series和DataFrame上定义了许多统计函数,最常见的是:
df_demo = df[['Height', 'Weight']]
df_demo.mean()
聚合函数,有一个公共参数axis,axis=0代表逐列聚合,axis=1表示逐行聚合
df_demo.mean(axis=1).head()
唯一值函数常用的四个函数:
代码:
#原本的数据样例
df_demo = df[['Gender','Transfer','Name']]
df_demo
Gender Transfer Name
0 Female N Gaopeng Yang
1 Male N Changqiang You
2 Male N Mei Sun
3 Female N Xiaojuan Sun
4 Male N Gaojuan You
... ... ... ...
195 Female N Xiaojuan Sun
196 Female N Li Zhao
197 Female N Chengqiang Chu
198 Male N Chengmei Shen
199 Male N Chunpeng Lv
200 rows × 3 columns
#现给Gender,Transfer两列去重
df_demo.drop_duplicates(['Gender','Transfer'])
Gender Transfer Name
0 Female N Gaopeng Yang
1 Male N Changqiang You
12 Female NaN Peng You
21 Male NaN Xiaopeng Shen
36 Male Y Xiaojuan Qin
43 Female Y Gaoli Feng
在未指定参数的情况下,keep默认first;
案例如下:
df_demo.drop_duplicates(['Gender', 'Transfer'], keep='last')
Gender Transfer Name
147 Male NaN Juan You
150 Male Y Chengpeng You
169 Female Y Chengquan Qin
194 Female NaN Yanmei Qian
197 Female N Chengqiang Chu
199 Male N Chunpeng Lv
替换函数有三类:
#原本的数据
df_demo = df[['Gender','Transfer','Name']]
df_demo
Gender Transfer Name
0 Female N Gaopeng Yang
1 Male N Changqiang You
2 Male N Mei Sun
3 Female N Xiaojuan Sun
4 Male N Gaojuan You
... ... ... ...
195 Female N Xiaojuan Sun
196 Female N Li Zhao
197 Female N Chengqiang Chu
198 Male N Chengmei Shen
199 Male N Chunpeng Lv
200 rows × 3 columns
#替换Gender,女替换为0,男替换为1
df['Gender'].replace({'Female':0, 'Male':1}).head()
0 0
1 1
2 1
3 0
4 1
Name: Gender, dtype: int64
逻辑替换包括了where和mask,这两个函数是完全对称的:where函数在传入条件为False的对应行进行替换,而mask在传入条件为True的对应行进行替换,当不指定替换值时,替换为缺失值(NAN)
s = pd.Series([-1, 1.2345, 100, -50])
s.where(s<0)
0 -1.0
1 NaN
2 NaN
3 -50.0
dtype: float64
s.where(s<0, 100)
0 -1.0
1 100.0
2 100.0
3 -50.0
dtype: float64
s.mask(s<0)
0 NaN
1 1.2345
2 100.0000
3 NaN
dtype: float64