目录
1.排序
通过sort_index方法对索引进行排序,默认为升序,降序排序时加参数ascending=False;通过sort_values方法对数值进行排序。
df2= pd.DataFrame(np.random.randn(3,3),columns = ['a','b','c'],
index = ['3','1','2'])
print(df2)
print(df2.sort_index())
print(df2.sort_values(by='c'))
#-------------------------------
a b c
3 1.806440 -0.434671 -0.231771
1 0.678005 0.928023 0.163997
2 1.087088 2.894730 -0.499704
a b c
1 0.678005 0.928023 0.163997
2 1.087088 2.894730 -0.499704
3 1.806440 -0.434671 -0.231771
a b c
2 1.087088 2.894730 -0.499704
3 1.806440 -0.434671 -0.231771
1 0.678005 0.928023 0.163997
2.数据统计
2.1数据汇总
可以通过sum方法对每列进行求和汇总,设置axis=1时可以实现按行汇总。
print('按列汇总:\n',df2.sum())
print('按行汇总:\n',df2.sum(axis = 1))
#---------------------------------------
按列汇总:
a 3.571533
b 3.388082
c -0.567478
dtype: float64
按行汇总:
3 1.139998
1 1.770025
2 3.482114
2.2数据去重计数
unique方法获取不重复的数组,nunique方法将数据去重后计数。
np.random.seed(971)
values_1 = np.random.randint(10, size=8)
groups = ['A','A','B','A','B','C','A','C']
df = pd.DataFrame({'group':groups, 'value_1':values_1})
display(df)
print('group的取值为:',df.group.unique())
print('group的取值个数为:',df.group.nunique())
#---------------------------------------------
group value_1
0 A 0
1 A 6
2 B 7
3 A 8
4 B 0
5 C 5
6 A 1
7 C 0
group的取值为: ['A' 'B' 'C']
group的取值个数为: 3
2.3频数统计
print('value_1的取值及其个数为:\n',df.value_1.value_counts())
#------------------------------------------------------------
value_1的取值及其个数为:
0 3
8 1
1 1
5 1
6 1
7 1
2.4 describe方法描述性统计
df2.describe()
#----------------------------------------
a b c
count 3.000000 3.000000 3.000000
mean 0.226340 -0.719726 0.463594
std 0.567288 1.040418 1.157900
min -0.397886 -1.893800 -0.219601
25% -0.015700 -1.123508 -0.204866
50% 0.366486 -0.353215 -0.190130
75% 0.538453 -0.132689 0.805192
max 0.710421 0.087838 1.800514
2.5 Pandas常用的描述性统计方法
方法 | 说明 |
median | 中位数 |
var | 方差 |
sem | 标准误差 |
skew | 样本偏度 |
quantile | 四分位数 |
ptp | 极差 |
std | 标准差 |
cov | 协方差 |
mode | 众数 |