社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

【Python】精选23个Pandas常用函数

机器学习初学者 • 3 年前 • 317 次点击  

公众号:尤而小屋
作者:Peter
编辑:Peter

从26个字母中精选出23个Pandas常用的函数,将它们的使用方法介绍给大家。其中o、y、z没有相应的函数。

import pandas as pd
import numpy as np

下面介绍每个函数的使用方法,更多详细的内容请移步官网:https://pandas.pydata.org/docs/reference/general_functions.html

assign函数

df = pd.DataFrame({
    'temp_c': [17.025.0]},
    index=['Portland''Berkeley'])
df

temp_c
Portland17.0
Berkeley25.0
# 生成新的字段

df.assign(temp_f=df['temp_c'] * 9 / 5 + 32)

temp_ctemp_f
Portland17.062.6
Berkeley25.077.0
df  # 原来DataFrame是不改变的

temp_c
Portland17.0
Berkeley25.0
如果是通过下面的方式来生成新的字段,那么原来的数据则会改变:
df["temp_f1"] = df["temp_c"] * 9 / 5 + 32
df

temp_ctemp_f1
Portland17.062.6
Berkeley25.077.0
df

temp_ctemp_f1
Portland17.062.6
Berkeley25.077.0

bool函数

返回单个Series或者DataFrame中单个元素的bool值:True或者False

pd.Series([True]).bool()
True
pd.Series([False]).bool()
False
pd.DataFrame({'col': [True]}).bool()
True
pd.DataFrame({'col': [False]}).bool()
False

# # 多个元素引发报错

# pd.DataFrame({'col': [True,False]}).bool()

concat函数

该函数是用来表示多个DataFrame的拼接,横向或者纵向皆可。

df1 = pd.DataFrame({
    "sid":["s1","s2"],
    "name":["xiaoming","Mike"]})
df1

sidname
0s1xiaoming
1s2Mike
df2 = pd.DataFrame({
    "sid":["s3","s4"],
    "name":["Tom","Peter"]})
df2

sidname
0s3Tom
1s4Peter
df3 = pd.DataFrame({
    "address":["北京","深圳"],             
    "sex":["Male","Female"]})
df3

addresssex
0北京Male
1深圳Female
# 使用1:纵向
pd.concat([df1,df2])

sidname
0s1xiaoming
1s2Mike
0s3Tom
1s4Peter
# 使用2:横向
pd.concat([df1,df3],axis=1)

sidnameaddresssex
0s1xiaoming北京Male
1s2Mike深圳Female

dropna函数

删除空值:可以对整个DataFrame删除,也可以指定某个属性来删除

df4 = pd.DataFrame({
    "sid":["s1","s2", np.nan],             
    "name":["xiaoming",np.nan, "Mike"]})
df4

sidname
0s1xiaoming
1s2NaN
2NaNMike
df4.dropna()

sidname
0s1xiaoming
df4.dropna(subset=["name"])

sidname
0s1xiaoming
2NaNMike

explode函数

爆炸函数的使用:将宽表转成长表。爆炸之后原数据是没有改变的

df5 = pd.DataFrame({
    "sid":["s1","s2"],       
    "phones":[["华为","小米","一加"],["三星","苹果"]]
                   })
df5

sidphones
0s1[华为, 小米, 一加]
1s2[三星, 苹果]
df5.explode("phones")

sidphones
0s1华为
0s1小米
0s1一加
1s2三星
1s2苹果
df5  # 原数据没有变

sid phones
0s1[华为, 小米, 一加]
1s2[三星, 苹果]

fillna函数

填充缺失值;可以整体填充,也可以对每个属性单独填充

df4

sidname
0s1xiaoming
1s2NaN
2NaNMike
df4.fillna({"sid":"s3","name":"Peter"})

sidname
0s1xiaoming
1s2Peter
2s3Mike

groupby函数

同组统计的功能

图解Pandas的groupby机制

# 借用这个结果
df6 = df5.explode("phones")
df6

sidphones
0s1华为
0s1小米
0s1一加
1s2三星
1s2苹果
df6.groupby("sid")["phones"].count()
sid
s1 3
s2 2
Name: phones, dtype: int64

head函数

查看前几行的数据,默认是前5行

df7 = pd.DataFrame({
    "sid":list(range(10)),                
    "name":list(range(80,100,2))})
df7

sidname
0080
1182
2284
3386
4488
5590
6692
7794
8896
9998
df7.head()   # 默认前5行

sidname
0080
1182
2284
3386
4488
df7.head(3)  # 指定前3行

sidname
0080
1182
2284

isnull函数

判断是否存在缺失值,超级常用的函数

df4

sidname
0s1xiaoming
1s2NaN
2NaNMike
df4.isnull()  # True表示缺失

sidname
0FalseFalse
1FalseTrue
2TrueFalse
df4.isnull().sum()  # 每个字段缺失的总和
sid     1
name 1
dtype: int64
df6.isnull().sum()   # 没有缺失值
sid       0
phones 0
dtype: int64

join函数

用于连接不同的DataFrame:图解Pandas数据合并:concat、join、append

df7 = pd.DataFrame({
    'key': ['K0''K1''K2''K3''K4''K5'],
    'A': ['A0''A1''A2''A3''A4''A5']})
df7

keyA
0K0A0
1K1A1
2K2A2
3K3A3
4K4A4
5K5A5
df8 = pd.DataFrame({
    'key': ['K0''K1''K2'],
    'B': ['B0''B1''B2']})
df8

keyB
0K0B0
1K1B1
2K2B2
df7.join(df8,lsuffix="_df7",rsuffix="_df8")

key_df7Akey_df8B
0K0A0K0B0
1K1A1K1B1
2K2A2K2 B2
3K3A3NaNNaN
4K4A4NaNNaN
5K5A5NaNNaN

kurt函数

查找数据的峰度值:从统计和数据角度出发,如何看待房价?

df9 = pd.DataFrame({
    "A":[1245441], 
    "B":[525432], 
    "C":[2016738], 
    "D":[1431726]}) 
df9

ABCD
01252014
142163
25547 17
344332
41286
df9.kurt()
A    3.936824
B 4.941512
C -1.745717
D -2.508808
dtype: float64

loc函数

loc就是location的缩写,定位查找数据

df9

ABCD
01252014
142163
2554717
344332
41286
df9.loc[1,:]  # 第一行全部列的数据
A     4
B 2
C 16
D 3
Name: 1, dtype: int64
df9.loc[1:3,"B"]  # 1到3行的B列
1     2
2 54
3 3
Name: B, dtype: int64

merge函数

同样也是数据的合并函数,类似SQL中的join,功能最为强大

df7

keyA
0K0A0
1K1A1
2K2A2
3K3A3
4K4A4
5K5A5
df8

keyB
0K0B0
1 K1B1
2K2B2
pd.merge(df7,df8)  # 默认how的参数是inner

keyAB
0K0A0B0
1K1A1B1
2K2A2B2
pd.merge(df7,df8,how="outer")  

keyAB
0K0A0B0
1K1A1B1
2K2A2B2
3K3A3NaN
4K4A4NaN
5K5A5NaN

nunique函数

用于统计数据的唯一值

df10 = pd.DataFrame({
    "sid":list("acbdefg"),
    "score":[9,8,9,7,8,9,3]
                    })
df10

sidscore
0a9
1c8
2b9
3d7
4e8
5f9
6g3
df10.nunique()
sid      7
score 4
dtype: int64

pct_change函数

计算当前时期和前一个时期的比值

s = pd.Series([909185])
s
0    90
1 91
2 85
dtype: int64
s.pct_change()
0         NaN
1 0.011111
2 -0.065934
dtype: float64
(91 - 90) / 90
0.011111111111111112
(85 - 91) / 91
-0.06593406593406594
# 和前两个时期相比
s.pct_change(periods=2
0         NaN
1 NaN
2 -0.055556
dtype: float64
# 如果存在空值,用填充方法
s = pd.Series([9091None85])
s  
0    90.0
1 91.0
2 NaN
3 85.0
dtype: float64
s.pct_change(fill_method='ffill')
0         NaN
1 0.011111
2 0.000000
3 -0.065934
dtype: float64

query函数

根据条件查询取值

df10

sidscore
0a9
1c8
2b 9
3d7
4e8
5f9
6g3
df10.query("score >= 8")

sidscore
0a9
1c8
2b9
4e8
5f9

rank函数

进行排名的函数,类似SQL的窗口函数功能:

df10

sidscore
0a9
1c8
2b9
3d7
4e8
5f9
6g3
df10["rank_10"] = df10["score"].rank()
df10

sidscorerank_10
0a96.0
1c83.5
2b96.0
3d72.0
4e83.5
5f96.0
6g31.0
df10["rank_10_max"] = df10["score"].rank(method="max")
df10

sidscorerank_10rank_10_max
0a96.07.0
1c83.54.0
2b96.07.0
3d72.02.0
4e83.54.0
5f96.07.0
6g31.01.0
df10["rank_10_min"] = df10["score"].rank(method="min")
df10

sidscorerank_10rank_10_maxrank_10_min
0a96.07.05.0
1c83.54.03.0
2b96.07.05.0
3d72.02.02.0
4e83.54.03.0
5f96.07.05.0
6g31.0 1.01.0

sort_values函数

根据数据进行排序的函数

df9

ABCD
01252014
142163
2554717
344332
41286
df9.sort_values("A")  # 默认是升序排列

ABCD
41286
142163
2554717
01252014
344332
# 先根据B升序,如果B相同,再根据D降序

df9.sort_values(["B","D"], ascending=[True,False])  

ABCD
41286
142163
344332
01252014
25 54717

tail函数

查看末尾的数据

df7.tail()

keyA
1K1A1
2K2A2
3K3A3
4K4A4
5K5A5
df7.tail(3)

keyA
3K3A3
4K4A4
5K5A5

unique函数

查找每个字段的唯一元素




    
df10

sidscorerank_10rank_10_maxrank_10_min
0a96.07.05.0
1c83.54.03.0
2b96.07.05.0
3d72.02.02.0
4e83.54.03.0
5f96.07.05.0
6g31.01.01.0
df10["score"].unique()
array([9, 8, 7, 3])



    
df10["rank_10"].unique()
array([6. , 3.5, 2. , 1. ])

value_counts函数

用于统计字段中每个唯一值的个数

df6

sidphones
0s1华为
0s1小米
0s1一加
1s2三星
1s2苹果
df6["sid"].value_counts()
s1    3
s2 2
Name: sid, dtype: int64
df6["phones"].value_counts()
华为    1
苹果 1
三星 1
一加 1
小米 1
Name: phones, dtype: int64

where函数

用于查找Series或者DataFrame中满足某个条件的数据

w = pd.Series(range(7))
w
0    0
1 1
2 2
3 3
4 4
5 5
6 6
dtype: int64
# 满足条件的显示;不满足的用空值代替
w.where(w>3)
0    NaN
1 NaN
2 NaN
3 NaN
4 4.0
5 5.0
6 6.0
dtype: float64
# 不满足条件的用8代替
w.where(w > 1 8)
0    8
1 8
2 2
3 3
4 4
5 5
6 6
dtype: int64

xs函数

该函数是用于多层级索引中用于获取指定索引处的值,使用一个关键参数来选择多索引特定级别的数据。

d = {'num_legs': [4422],
     'num_wings': [0022],
     'class': ['mammal''mammal''mammal''bird'],
     'animal': ['cat''dog''bat''penguin'],
     'locomotion': ['walks''walks''flies''walks']}
# 生成数据
df11 = pd.DataFrame(data=d)
# 重置索引
df11 = df11.set_index(['class''animal''locomotion'])
df11



num_legsnum_wings
classanimallocomotion

mammalcatwalks40
dogwalks40
batflies22
birdpenguinwalks22
# 获取指定索引的值
df11.xs('mammal')  


num_legsnum_wings
animallocomotion

catwalks40
dogwalks40
batflies22
# 指定多个索引处的值
df11.xs(('mammal''dog'))

num_legsnum_wings
locomotion

walks40
# 获取指定索引和级别(level)的值
df11.xs('cat', level=1)


num_legsnum_wings
classlocomotion

mammalwalks40
df11



num_legsnum_wings
classanimallocomotion

mammalcatwalks40
dogwalks40
batflies22
birdpenguinwalks22
# 获取多个索引和级别的值
df11.xs(('bird''walks'),level=[0'locomotion'])

num_legsnum_wings
animal

penguin22
# 获取指定列和轴上的值
df11.xs('num_wings', axis=1)
class   animal   locomotion
mammal cat walks 0
dog walks 0
bat flies 2
bird penguin walks 2
Name: num_wings, dtype: int64
往期精彩 回顾




站qq群955171419,加入微信群请扫码:
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/125155
 
317 次点击