精选23个Pandas函数

公众号:尤而小屋
作者:Peter
编辑: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.0, 25.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函数

删除空值

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
sidphones
0s1[华为, 小米, 一加]
1s2[三星, 苹果]

fillna函数

填充缺失值

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

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:

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
2K2A2K2B2
3K3A3NaNNaN
4K4A4NaNNaN
5K5A5NaNNaN

kurt函数

查找数据的峰度值

df9 = pd.DataFrame({
    "A":[12, 4, 5, 44, 1], 
    "B":[5, 2, 54, 3, 2], 
    "C":[20, 16, 7, 3, 8], 
    "D":[14, 3, 17, 2, 6]}) 
df9
ABCD
01252014
142163
2554717
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
1K1B1
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([90, 91, 85])
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([90, 91, None, 85])
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
2b9
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.01.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
2554717

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': [4, 4, 2, 2],
     'num_wings': [0, 0, 2, 2],
     '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'))
/Applications/downloads/anaconda/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:2881: PerformanceWarning: indexing past lexsort depth may impact performance.
  return runner(coro)
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值