Pandas必掌握的95道精选题型!!

本文详述了使用Pandas进行数据分析时的95个核心操作,包括创建Series、DataFrame、数据类型转换、操作行列、缺失值处理、统计计算、数据可视化以及文件读写等,旨在帮助读者深入理解和掌握Pandas库。
摘要由CSDN通过智能技术生成


本人学习比较抠字眼,所以加的注释会比较详细。希望大家可以从中学到东西!

文章目录

概念简介

pandas是Python的数据分析包。应用最广泛的pandas数据类型是Series和DataFrame。

DataFrame和Series是pandas中最常见的2种数据结构。

Series是一种类似于一维数组的对象,是由一组数据以及一组与之相关联的标签(即索引)组成的,具体的表现形式就是索引在左边,值在右边。可以理解为一维数组,它和一维数组的区别,在于Series具有索引。

DataFrame是一个表型的数据结构,它含有一组有序的列,每列间可以是不同的数据类型(数值,字符串,布尔值等)。DataFrame既有行索引又有列索引。类似于excel表格。

1.用列表创建Series

import pandas as pd
import numpy as np
s = pd.Series([1, 3, 5, np.nan, 6, 8]) #用值列表生成 Series(一维数据) 时,Pandas 默认自动生成整数索引
print(s)
print('\n')#不同结果之间空行
print(s.index)#输出s的索引

输出结果:

0    1.0
1    3.0
2    5.0
3    NaN
4    6.0
5    8.0
dtype: float64


RangeIndex(start=0, stop=6, step=1)

2.将Series转换成一维数组

s.to_numpy() #Numpy是数组;s来源于题1。

输出结果:

array([ 1.,  3.,  5., nan,  6.,  8.])

3.用数组创建Series

pd.Series(np.arange(7)) #索引默认从0开始;arange()用于创建等差数组

输出结果:

0    0
1    1
2    2
3    3
4    4
5    5
6    6
dtype: int32

4.用字典创建Series

s = pd.Series({
   'a':1, 'b':2, 'c':3}) #s来源于题1。
print(s)
print('\n')#不同结果之间空行
print(s.values) #字典是key:value形式,输出其中的value
print('\n')#不同结果之间空行
print(s.index) #输出索引

输出结果:

a    1
b    2
c    3
dtype: int64


[1 2 3]


Index(['a', 'b', 'c'], dtype='object')

5.用随机数创建Series

pd.Series(np.random.randn(5),index=('a','b','c','d','e'))#randn产生标准正态分布的随机数

输出结果:

a    0.184519
b    0.937082
c    0.731000
d    1.361556
e   -0.326238
dtype: float64

6.用Series 组成的字典来创建 DataFrame

pd.DataFrame({
   'a': pd.Series([1, 2, 3]),
              'b': pd.Series([4, 5, 6])})

输出结果:

a b
0 1 4
1 2 5
2 3 6

7.用列表组成的字典来创建 DataFrame

pd.DataFrame({
   'a': [1, 2, 3],
              'b': [4, 5, 6]})

输出结果:

a b
0 1 4
1 2 5
2 3 6

8.用字典组成的列表来创建 DataFrame

pd.DataFrame([{
   'a': 1, 'b': 4},
              {
   'a': 2, 'b': 5},
              {
   'a': 3, 'b': 6}])

输出结果:

a b
0 1 4
1 2 5
2 3 6

9.对比DataFrame与Series区别

pd.DataFrame(np.random.randint(5,size=(2,))) #有列索引;(2,)这个多个逗号代表是元组

输出结果:

0
0 3
1 3
pd.Series(np.random.randint(5,size=(2,))) #无列索引

输出结果:

0    1
1    3
dtype: int32

10.用不同字典方式创建DataFrame

df=pd.DataFrame({
   'A': 1.,
                 'B': pd.Timestamp('20130102'),#Timestamp时间戳
                 'C': pd.Series(1, index=list(range(4)), dtype='float32'),
                 'D': np.array([3] * 4, dtype='int32'),
                 'E': pd.Categorical(["test", "train", "test", "train"]), #Categorical类别函数
                 'F': 'foo'})
print(df)

输出结果:

     A          B    C  D      E    F
0  1.0 2013-01-02  1.0  3   test  foo
1  1.0 2013-01-02  1.0  3  train  foo
2  1.0 2013-01-02  1.0  3   test  foo
3  1.0 2013-01-02  1.0  3  train  foo

11.查看DataFrame数据类型

df.dtypes #可以看到df的列有不同的数据类型。NumPy 数组只有一种数据类型,DataFrame 每列的数据类型各不相同;df来源于题10

输出结果:

A           float64
B    datetime64[ns]
C           float32
D             int32
E          category
F            object
dtype: object

12.将DataFrame转换成二维数组

df.to_numpy() #不包含行索引与列索引;df来源于题10

输出结果:

array([[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'],
       [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo']],
      dtype=object)

13.查看 DataFrame头部数据

df.head(2) #前两行;df来源于题10

输出结果:

A B C D E F
0 1.0 2013-01-02 1.0 3 test foo
1 1.0 2013-01-02 1.0 3 train foo

14.查看 DataFrame尾部数据

df.tail(2) #后两行;df来源于题10

输出结果:

A B C D E F
2 1.0 2013-01-02 1.0 3 test foo
3 1.0 2013-01-02 1.0 3 train foo

15.查看 DataFrame后三行数据

df.loc[[1,2,3]] #注意有两层中括号;df来源于题10

输出结果:

A B C D E F
1 1.0 2013-01-02 1.0 3 train foo
2 1.0 2013-01-02 1.0 3 test foo
3 1.0 2013-01-02 1.0 3 train foo

16.查看 DataFrame后三行ABC列数据

df.loc[[1,2,3],'A':'C'] #df来源于题10

输出结果:

A B C
1 1.0 2013-01-02 1.0
2 1.0 2013-01-02 1.0
3 1.0 2013-01-02 1.0

17.查看 DataFrame后三行C列往后的数据

df.loc[[1,2,3],'C':] #df来源于题10

输出结果:

C D E F
1 1.0 3 train foo
2 1.0 3 test foo
3 1.0 3 train foo

18.查看 DataFrame行索引

df.index #df来源于题10

输出结果:

Int64Index([0, 1, 2, 3], dtype='int64')

19.查看 DataFrame列索引

df.columns #df来源于题10
Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')

20.查看 DataFrame形状

df.shape #4行6列;df来源于题10

输出结果:

(4, 6)

21.按条件将E列test选出来

df[df['E'].isin(['test'])] #df来源于题10

输出结果:

A B C D E F
0 1.0 2013-01-02 1.0 3 test foo
2 1.0 2013-01-02 1.0 3 test foo

22.用含日期索引的 NumPy 数组生成 DataFrame

dates = pd.date_range('20200101', periods=6) 
dates

输出结果:

DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
               '2020-01-05', '2020-01-06'],
              dtype='datetime64[ns]', freq='D')

23.生成含有随机数的DataFrame

np.random.seed(100) #seed是随机数种子,利用随机数种子,每次生成的随机数相同。比如保持100,每次运行生成的随机数不会变,除非改掉100这个数字。
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD')) # index为行索引,column为列索引;randn产生标准正态分布的随机数
df

输出结果:

A B C D
2020-01-01 -1.749765 0.342680 1.153036 -0.252436
2020-01-02 0.981321 0.514219 0.221180 -1.070043
2020-01-03 -0.189496 0.255001 -0.458027 0.435163
2020-01-04 -0.583595 0.816847 0.672721 -0.104411
2020-01-05 -0.531280 1.029733 -0.438136 -1.118318
2020-01-06 1.618982 1.541605 -0.251879 -0.842436

24.快速查看DataFrame的各种统计指标

df.describe() #count计数,mean平均数,std标准差,min最小值,25%下四分位数,75%上四分位数,50%中位数,max最大值;df来源于题23

输出结果:

A B C D
count 6.000000 6.000000 6.000000 6.000000
mean -0.075639 0.750014 0.149816 -0.492080
std 1.205835 0.484950 0.657494 0.619106
min -1.749765 0.255001 -0.458027 -1.118318
25% -0.570516 0.385565 -0.391572 -1.013141
50% -0.360388 0.665533 -0.015350 -0.547436
75% 0.688617 0.976511 0.559836 -0.141417
max 1.618982 1.541605 1.153036 0.435163

25.DataFrame的转置

df.T #行列颠倒;df来源于题23

输出结果:

2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06
A -1.749765 0.981321 -0.189496 -0.583595 -0.531280 1.618982
B 0.342680 0.514219 0.255001 0.816847 1.029733 1.541605
C 1.153036 0.221180 -0.458027 0.672721 -0.438136 -0.251879
D -0.252436 -1.070043 0.435163 -0.104411 -1.118318 -0.842436

26.按轴排序

df.sort_index(axis=0, ascending=False)#axis=0按照index排序,axis=1按照column排序;ascending=False代表降序,ascending=True代表升序;df来源于题23

输出结果:

A B C D
2020-01-06 1.618982 1.541605 -0.251879 -0.842436
2020-01-05 -0.531280 1.029733 -0.438136 -1.118318
2020-01-04 -0.583595 0.816847 0.672721 -0.104411
2020-01-03 -0.189496 0.255001 -0.458027 0.435163
2020-01-02 0.981321 0.514219 0.221180 -1.070043
2020-01-01 -1.749765 0.342680 1.153036 -0.252436

27.按值排序

df.sort_values(by='B') #sort_values默认升序;若想降序排,则改成 df.sort_values(by='B',ascending=False) 即可;df来源于题23

输出结果:

A B C D
2020-01-03 -0.189496 0.255001 -0.458027 0.435163
2020-01-01 -1.749765 0.342680 1.153036 -0.252436
2020-01-02 0.981321 0.514219 0.221180 -1.070043
2020-01-04 -0.583595 0.816847 0.672721 -0.104411
2020-01-05 -0.531280 1.029733 -0.438136 -1.118318
2020-01-06 1.618982 1.541605 -0.251879 -0.842436

28.获取DataFrame中的某一列

方法一

 df['A']#df来源于题23

输出结果:

2020-01-01   -1.749765
2020-01-02    0.981321
2020-01-03   -0.189496
2020-01-04   -0.583595
2020-01-05   -0.531280
2020-01-06    1.618982
Freq: D, Name: A, dtype: float64

方法二

 df.A #df来源于题23

输出结果:

2020-01-01   -1.749765
2020-01-02    0.981321
2020-01-03   -0.189496
2020-01-04   -0.583595
2020-01-05   -0.531280
2020-01-06    1.618982
Freq: D, Name: A, dtype: float64

29.获取DataFrame中的某几列

df.iloc[:, 1:3] #iloc()通过行号、列号选取数据,loc()通过index、column选取数据;df来源于题23

输出结果:

B C
2020-01-01 0.342680 1.153036
2020-01-02 0.514219 0.221180
2020-01-03 0.255001 -0.458027
2020-01-04 0.816847 0.672721
2020-01-05 1.029733 -0.438136
2020-01-06 1.541605 -0.251879

30.用切片方式获取DataFrame中的某几行

方法一

df[0:3] #用切片的方式取前三行,前三行索引是0、1、2,分别对应第1行、第2行、第3行;df来源于题23

输出结果:

A B C D
2020-01-01 -1.749765 0.342680 1.153036 -0.252436
2020-01-02 0.981321 0.514219 0.221180 -1.070043
2020-01-03 -0.189496 0.255001 -0.458027 0.435163

方法二

df['20200101':'20200103'] #df来源于题23

输出结果:

A B C D
2020-01-01 -1.749765 0.342680 1.153036 -0.252436
2020-01-02 0.981321 0.514219 0.221180 -1.070043
2020-01-03 -0.189496 0.255001 -0.458027 0.435163

方法三

df.iloc[0:3, :] #df来源于题23

输出结果:

A B C D
2020-01-01 -1.749765 0.342680 1.153036 -0.252436
2020-01-02 0.981321 0.514219 0.221180 -1.070043
2020-01-03 -0.189496 0.255001 -0.458027 0.435163

方法四

df[df.index.isin
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值