pandas教程(快速入门,纯干货无废话)

目录

一、前言

二、Pandas内置数据结构 

2-1.Series结构:

2-2.DataFrame结构

三、使用方法 

3-1.Series的使用

3-1-1.创建Series对象:

1) 列表创建Series对象

2) ndarray创建Series对象

3) dict创建Series对象

4) 标量创建Series对象

3-1-2访问Series数据

1) 位置索引访问

 2) 索引标签访问

3-1-3.Series常用属性

3-1-4:Series常用方法 

1) head()&tail()查看数据

2) isnull()&nonull()检测缺失值

3-2.DataFrame的使用

3-2-1.创建 DataFrame 对象

1) 列表创建DataFame对象

2) 字典嵌套列表创建

3) 列表嵌套字典创建DataFrame对象

4) Series创建DataFrame对象

3-2-2.操作DataFrame

3-2-2-1.列索引操作DataFrame

1) 列索引选取数据列

2) 列索引添加数据列

3) 列索引删除数据列

3-2-2-2.行索引操作DataFrame

1) 标签索引选取

2) 整数索引选取

3) 切片操作多行选取

4) 添加数据行

5) 删除数据行

3-2-3.常用属性和方法汇总 


一、前言

        本文不会详细介绍pandas各种优势、特点、用途这些无关紧要的东西,主要围绕SeriesDataFrame这两种数据结构的用法来进行讲解,旨在帮助读者花最少的时间了解pandas该怎么用,适合了解但不熟练的同学用来加强巩固复习。也相当于作者自己的一篇复习笔记,主要参考该网址内容:Pandas Series入门教程

        下面开始正文部分

二、Pandas内置数据结构 

        pandas主要有两种内置数据结构:SeriesDataFrame

2-1.Series结构:

        它是一种类似于一维数组的结构,由一组数据值标签组成,其中标签与数据值之间是一一对应的关系,类似于python的字典,可以参考下图理解。

 2-2.DataFrame结构

        它是一个表格型的数据结构,既有行标签,又有列标签,类似于excel。其结构图示意图,如下所示:

三、使用方法 

3-1.Series的使用

3-1-1.创建Series对象:

        pandas 使用 Series()  函数来创建 Series 对象,通过这个对象可以调用相应的方法和属性,从而达到处理数据的目的:

        s=pd.Series( data, index, dtype, copy)

参数说明如下所示:

参数名称描述
data输入的数据,可以是列表、常量、ndarray 数组等。
index索引值必须是惟一的,如果没有传递索引,则默认为 np.arrange(n)。
dtypedtype表示数据类型,如果没有提供,则会自动判断得出。
copy表示对 data 进行拷贝,默认为 False。
1) 列表创建Series对象
import pandas as pd
s = pd.Series([1, 'a', '你好'])
print(s)

输出结果如下:

0     1
1     a
2    你好
dtype: object 

2) ndarray创建Series对象

使用默认索引,创建 Series 序列对象:

import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data)
print (s)

输出结果如下:

0   a
1   b
2   c
3   d
dtype: object

        上述示例中没有传递任何索引,所以索引默认从 0 开始分配 ,其索引范围为 0 到len(data)-1,即 0 到 3。这种设置方式被称为“隐式索引”。
        除了上述方法外,你也可以使用“显式索引”的方法定义索引标签,示例如下:

import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
#自定义索引标签(即显示索引)
s = pd.Series(data,index=[100,101,102,103])
print(s)

输出结果:

100  a
101  b
102  c
103  d
dtype: object
3) dict创建Series对象
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data)
print(s)

输出结果:

a 0.0
b 1.0
c 2.0
dtype: float64
4) 标量创建Series对象

如果 data 是标量值,则必须提供索引,示例如下:

import pandas as pd
import numpy as np
s = pd.Series(5, index=[0, 1, 2, 3])
print(s)

输出如下:

0  5
1  5
2  5
3  5
dtype: int64

标量值按照 index 的数量进行重复,并与其一一对应。

3-1-2访问Series数据

        分为两种方式,一种是位置索引访问,另一种是索引标签访问。

1) 位置索引访问

这种访问方式和操作列表相似,使用元素自身的下标进行访问,而且支持切片

示例1,使用下标访问单个元素值:

import pandas as pd
s = pd.Series([-6, 6, 6.66, 'a', '你好'])
print(s[0])

输出结果

示例 2,使用切片访问 多个元素值

import pandas as pd
s = pd.Series([-6, 6, 6.66, 'a', '你好'])
print(s[2:5])

输出结果

2    6.66
3       a
4      你好
dtype: object

 2) 索引标签访问

这种访问方法类似于python的字典

示例1,使用索标签访问单个元素值:

import pandas as pd
s = pd.Series([-6, 6, 6.66, 'a', '你好'], index=['a', 'b', 'c', 'd', 'e'])
print(s['e'])

输出结果 

你好

示例 2,使用索引标签访问多个元素值 

import pandas as pd
s = pd.Series([-6, 6, 6.66, 'a', '你好'], index=['a', 'b', 'c', 'd', 'e'])
print(s[['a', 'c', 'b']])
import pandas as pd
s = pd.Series([-6, 6, 6.66, 'a', '你好'], index=['a', 'b', 'c', 'd', 'e'])
print(s[['a', 'c', 'b']])

 3-1-3.Series常用属性

下面我们介绍 Series 的常用属性和方法。在下表列出了 Series 对象的常用属性。

名称属性
axes以列表的形式返回所有行索引标签。
dtype返回对象的数据类型。
empty返回一个空的 Series 对象。
ndim返回输入数据的维数。
size返回输入数据的元素数量。
values以 ndarray 的形式返回 Series 对象。
index返回一个RangeIndex对象,用来描述索引的取值范围。
import pandas as pd
s = pd.Series([-6, 6, 6.66, 'a', '你好'], index=['a', 'b', 'c', 'd', 'e'])
print(s.axes)
print(s.dtype)
print(s.empty)
print(s.ndim)
print(s.size)
print(s.values)
print(s.index)

输出结果

[Index(['a', 'b', 'c', 'd', 'e'], dtype='object')]
object
False
1
5
[-6 6 6.66 'a' '你好']
Index(['a', 'b', 'c', 'd', 'e'], dtype='object') 

3-1-4:Series常用方法 

1) head()&tail()查看数据

        如果想要查看 Series 的某一部分数据,可以使用 head(n) 或者 tail(n) 方法。其中 head() 返回前 n 行数据,默认显示前 5 行数据。示例如下:

import pandas as pd
import numpy as np
s = pd.Series(np.random.randn(5))
print ("The original series is:")
print (s)
#返回前三行数据
print (s.head(3))

输出结果:

原系列输出结果:
0    1.249679
1    0.636487
2   -0.987621
3    0.999613
4    1.607751
head(3)输出:
dtype: float64
0    1.249679
1    0.636487
2   -0.987621
dtype: float64

 tail() 返回的是后 n 行数据,默认为后 5 行。示例如下:

import pandas as pd
import numpy as np
s = pd.Series(np.random.randn(4))
#原series
print(s)
#输出后两行数据
print (s.tail(2))

输出结果:

原Series输出:
0    0.053340
1    2.165836
2   -0.719175
3   -0.035178
输出后两行数据:
dtype: float64
2   -0.719175
3   -0.035178
dtype: float64
2) isnull()&nonull()检测缺失值

isnull() 和 nonull() 用于检测 Series 中的缺失值。所谓缺失值,顾名思义就是值不存在、丢失、缺少。

  • isnull():如果为值不存在或者缺失,则返回 True。
  • notnull():如果值不存在或者缺失,则返回 False。
import pandas as pd
#None代表缺失数据
s=pd.Series([1,2,5,None])
print(pd.isnull(s))  #是空值返回True
print(pd.notnull(s)) #空值返回False

输出结果:

0    False
1    False
2    False
3     True
dtype: bool

notnull():
0     True
1     True
2     True
3    False
dtype: bool

3-2.DataFrame的使用

3-2-1.创建 DataFrame 对象

import pandas as pd

pd.DataFrame( data, index, columns, dtype, copy)

参数说明:

参数名称说明
data输入的数据,可以是 ndarray,series,list,dict,标量以及一个 DataFrame。
index行标签,如果没有传递 index 值,则默认行标签是 np.arange(n),n 代表 data 的元素个数。
columns列标签,如果没有传递 columns 值,则默认列标签是 np.arange(n)。
dtypedtype表示每一列的数据类型。
copy默认为 False,表示复制数据 data。
1) 列表创建DataFame对象
import pandas as pd

data = [['Alex',10],['Bob',12],['Clarke',13]]

df = pd.DataFrame(data,columns=['Name','Age'])

print(df)

输出结果:

      Name      Age
0     Alex      10
1     Bob       12
2     Clarke    13
2) 字典嵌套列表创建

无自定义标签

import pandas as pd

data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}

df = pd.DataFrame(data)

print(df)

输出结果:

      Age      Name
0     28        Tom
1     34       Jack
2     29      Steve
3     42      Ricky

有自定义标签:

import pandas as pd

data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}

df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])

print(df)

输出结果如下:

         Age    Name
rank1    28      Tom
rank2    34     Jack
rank3    29    Steve
rank4    42    Ricky
3) 列表嵌套字典创建DataFrame对象
import pandas as pd

data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]

df = pd.DataFrame(data, index=['first', 'second'])

print(df)

输出结果:

        a   b       c
first   1   2     NaN
second  5   10   20.0
import pandas as pd

data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]

df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])

df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])

print(df1)

print(df2)

输出结果:

#df2输出
         a  b
first    1  2
second   5  10

#df1输出
         a  b1
first    1  NaN
second   5  NaN

注意:因为 b1 在字典键中不存在,所以对应值为 NaN。

4) Series创建DataFrame对象
import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),

    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)

print(df)

输出结果如下:

      one    two
a     1.0    1
b     2.0    2
c     3.0    3
d     NaN    4

注意:对于 one 列而言,此处虽然显示了行索引 'd',但由于没有与其对应的值,所以它的值为 NaN。

3-2-2.操作DataFrame

3-2-2-1.列索引操作DataFrame
1) 列索引选取数据列
import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),

'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)

print(df ['one'])

输出结果:

a     1.0
b     2.0
c     3.0
d     NaN
Name: one, dtype: float64
2) 列索引添加数据列

使用 columns 列索引表标签可以实现添加新的数据列,示例如下:

import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),

'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)

#使用df['列']=值,插入新的数据列

df['three']=pd.Series([10,20,30],index=['a','b','c'])

print(df)

#将已经存在的数据列做相加运算

df['four']=df['one']+df['three']

print(df)

输出结果:

使用列索引创建新数据列:
     one   two   three
a    1.0    1    10.0
b    2.0    2    20.0
c    3.0    3    30.0
d    NaN    4    NaN

已存在的数据列做算术运算:
      one   two   three    four
a     1.0    1    10.0     11.0
b     2.0    2    20.0     22.0
c     3.0    3    30.0     33.0
d     NaN    4     NaN     NaN

还可以使用 insert() 方法插入新的列,示例如下:

import pandas as pd
info=[['Jack',18],['Helen',19],['John',17]]
df=pd.DataFrame(info,columns=['name','age'])
print(df)
#注意是column参数
#数值1代表插入到columns列表的索引位置
df.insert(1,column='score',value=[91,90,75])
print(df)

输出结果:

添加前:
    name  age
0   Jack   18
1  Helen   19
2   John   17

添加后:
    name  score  age
0   Jack     91   18
1  Helen     90   19
2   John     75   17
3) 列索引删除数据列

通过 del 和 pop() 都能够删除 DataFrame 中的数据列。示例如下:

import pandas as pd
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
'three' : pd.Series([10,20,30], index=['a','b','c'])}
df = pd.DataFrame(d)
print ("Our dataframe is:")
print(df)
#使用del删除
del df['one']
print(df)
#使用pop方法删除
df.pop('two')
print (df)

输出结果:

原DataFrame:
      one   three  two
a     1.0    10.0   1
b     2.0    20.0   2
c     3.0    30.0   3
d     NaN     NaN   4

使用del删除 first:
      three    two
a     10.0     1
b     20.0     2
c     30.0     3
d     NaN      4

使用 pop()删除:
   three
a  10.0
b  20.0
c  30.0
d  NaN
3-2-2-2.行索引操作DataFrame
1) 标签索引选取

可以将行标签传递给 loc 函数,来选取数据。示例如下:

import pandas as pd
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print(df.loc['b'])

输出结果:

one 2.0

two 2.0

Name: b, dtype: float64

2) 整数索引选取

通过将数据行所在的索引位置传递给 iloc 函数,也可以实现数据行选取。示例如下:

import pandas as pd
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print (df.iloc[2])

输出结果:

one    3.0
two    3.0
Name: c, dtype: float64

3) 切片操作多行选取

您也可以使用切片的方式同时选取多行。示例如下:

import pandas as pd
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
#左闭右开
print(df[2:4])

输出结果:

   one  two
c  3.0    3
d  NaN    4

4) 添加数据行

使用 _append() 函数,可以将新的数据行添加到 DataFrame 中,该函数会在行末追加数据行。

注意:append前面有一个下划线。

示例如下:

import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
#在行末追加新数据行
df = df._append(df2)
print(df)

运行结果:

   a  b
0  1  2
1  3  4
0  5  6
1  7  8 

5) 删除数据行

您可以使用行索引标签,从 DataFrame 中删除某一行数据。如果索引标签存在重复,那么它们将被一起删除。示例如下:

import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
df = df.append(df2)
print(df)
#注意此处调用了drop()方法
df = df.drop(0)
print (df)

输出结果:

   a  b
1  3  4
1  7  8

在上述的示例中,默认使用 range(2) 生成了行索引,并通过 drop(0) 同时删除了两行数据。

3-2-3.常用属性和方法汇总 

名称属性&方法描述
T行和列转置。
axes返回一个仅以行轴标签和列轴标签为成员的列表。
dtypes返回每列数据的数据类型。
emptyDataFrame中没有数据或者任意坐标轴的长度为0,则返回True。
ndim轴的数量,也指数组的维数。
shape返回一个元组,表示了 DataFrame 维度。
sizeDataFrame中的元素数量。
values使用 numpy 数组表示 DataFrame 中的元素值。
head()返回前 n 行数据。
tail()返回后 n 行数据。
shift()将行或列移动指定的步幅长度
  • 26
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Pandas是一种基于NumPy的数据分析工具,它可以帮助我们对数据进行清洗、编辑和分析等工作。掌握Pandas的常规用法是构建机器学习模型的第一步。首先,我们需要安装Pandas。如果已经安装了Anaconda,可以直接使用Anaconda自带的包管理工具来安装Pandas。如果没有安装Anaconda,可以使用Python自带的包管理工具pip来安装Pandas,命令为pip install pandas。安装完成后,我们可以导入Pandas库并查询相应的版本信息。通常,我们还会导入NumPy库,因为Pandas和NumPy常常结合在一起使用。导入Pandas库的命令为import pandas as pd,导入NumPy库的命令为import numpy as np。要查询Pandas的版本信息,可以使用print(pd.__version__)命令。接下来,我们可以学习Pandas的数据类型,包括Series和DataFrame。Series是一种一维的数据结构,类似于数组或列表,而DataFrame是一种二维的数据结构,类似于表格。在学习Pandas的过程中,我们可以通过导入Excel数据、输出Excel数据、数据概览、数据查看、数据清洗、数据选择、数据排序、数据分组、数据透视、数据合并和数据可视化等操作来熟悉Pandas的用法。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *2* [非常全面的Pandas入门教程](https://blog.csdn.net/weixin_44489066/article/details/89494395)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [pandas 快速入门教程](https://blog.csdn.net/down_12345/article/details/105345429)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值