Pandas(九)–数据采样

  • Post author:
  • Post category:其他



目录


sample() 采样函数


随机采样


有条件采样


恒定速率采样


获取数据剩余部分


resample()采样函数


降采样


升采样


频率转换asfreq()


插值处理


sample() 采样函数

随机采样

随机抽样,是统计学中常用的一种方法,它可以帮助我们从大量的数据中快速地构建出一组数据分析模型。在 Pandas 中,如果想要对数据集进行随机抽样,需要使用 sample() 函数。

sample() 函数的语法格式如下:

DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)

参数说明如下表所示:

参数名称 参数说明
n 表示要抽取的行数。
frac 表示抽取的比例,比如 frac=0.5,代表抽取总体数据的50%。
replace 布尔值参数,表示是否以有放回抽样的方式进行选择,默认为 False,取出数据后不再放回。
weights 可选参数,代表每个样本的权重值,参数值是字符串或者数组。
random_state 可选参数,控制随机状态,默认为 None,表示随机数据不会重复;若为 1 表示会取得重复数据。
axis 表示在哪个方向上抽取数据(axis=1 表示列/axis=0 表示行)。

该函数返回与数据集类型相同的新对象,相当于 numpy.random.choice()。构建示例数据:

  1. import pandas as pd
  2. dict = {‘name’:[“Jack”, “Tom”, “Helen”, “John”],’age’: [28, 39, 34, 36],’score’:[98,92,91,89]}
  3. info = pd.DataFrame(dict)
#默认随机选择两行
info.sample(n=2)
输出结果:
    name  age  score
2  Helen   34     91
0   Jack   28     98

#随机选择两列
info.sample(n=2, axis=1)
输出结果:
   name  age  score
   age  score
0   28     98
1   39     92
2   34     91
3   36     89

#随机抽取3个数据
info['name'].sample(n=3)
输出结果:
1      Tom
3     John
2    Helen
Name: name, dtype: object

#总体的50%
info.sample(frac=0.5, replace=True)
输出结果:
    name  age  score
2  Helen   34     91
0   Jack   28     98

#age序列为权重值,并且允许重复数据出现
info.sample(n=2, weights='age', random_state=1)
输出结果:
    name  age  score
1    Tom   39     92
2  Helen   34     91

有条件采样

带条件采样允许仅提取满足给定条件的一些行。必须指定条件。

首先,满足列值

sepal width (cm)

小于 3

条件

的行:

condition = df['sepal width (cm)'] < 3

变量

condition

是一系列大小相同的

df

,包含

True/False

,取决于行是否满足条件。

然后,检索与满足上述条件的行相关联的

索引

true_index = condition[condition == True].index

如果有 57 行满足条件,因此最多可以采样 57 行。

最后,通过

sample()

函数可用于按如下条件进行

采样

subset = df[condition].sample(n = 10)

恒定速率采样

两个相邻样本之间的距离恒定

# 首先,指定费率
rate = 10
# 然后,提取样本,输出
subset = df[::rate]

获取数据剩余部分

提取数据集的子集后,还可以提取剩余部分。可以采用两种可能的解决方案来提取数据集的剩余部分。两种解决方案产生相同的结果。

第一种解决方案将提取的数据帧 (

subset

)的行删除到原始数据帧中

df

,并将结果存储在新的数据帧中。这可以通过将要删除的索引列表传递给


drop()

函数

来实现:

remaining = df.drop(labels=subset.index)

第二种解决方案仅选择原始数据帧中的行,

df

其中索引

不在提取的数据帧的索引列表



subset

remaining = df[~df.index.isin(subset.index)]

resample()采样函数

也称时间序列采样和数据重采样,其将

时间序列从一个频率转换至另一个频率的过程

,它主要有两种实现方式:降采样和升采样,降采样指将高频率的数据转换为低频率,升采样则与其恰好相反。

方法 说明
降采样 将高频率(间隔短)数据转换为低频率(间隔长)。
升采样 将低频率数据转换为高频率。

降采样

import pandas as pd
import numpy as np
rng = pd.date_range('1/1/2021',periods=100, freq='D')
ts = pd.Series(np.random.randn(len(rng)),index=rng)

# 按天计数的频率转换为按月计数。
# 降采样后并聚合
ts.resample('M').mean()

输出结果:
2021-01-31    0.046598
2021-02-28    0.000194
2021-03-31   -0.162896
2021-04-30   -0.395149
Freq: M, dtype: float64

如果只想看到月份,那么您可以设置kind=period如下所示:
ts.resample('M',kind='period').mean()

输出结果:
2021-01    0.046598
2021-02    0.000194
2021-03   -0.162896
2021-04   -0.395149
Freq: M, dtype: float64

升采样

import pandas as pd
import numpy as np
rng = pd.date_range('1/1/2021', periods=20, freq='3D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
print(ts.head())

# 升采样是将低频率(时间间隔)转换为高频率
# 然后,使用asfreq()在原数据基础上实现频率转换
ts.resample('D').asfreq().head()

输出结果:
升采样前:
2021-01-01    0.869743
2021-01-04   -1.105558
2021-01-07   -0.395761
2021-01-10   -1.163647
2021-01-13    0.367996
Freq: 3D, dtype: float64

升采样后:
2021-01-01    0.869743
2021-01-02         NaN
2021-01-03         NaN
2021-01-04   -1.105558
2021-01-05         NaN
Freq: D, dtype: float64

频率转换asfreq()

该方法不仅能够实现频率转换,还可以保留原频率对应的数值,同时也可以单独使用,示例如下:

index = pd.date_range('1/1/2021', periods=6, freq='T')
series = pd.Series([0.0, None, 2.0, 3.0,4.0,5.0], index=index)
df = pd.DataFrame({'s':series})
print(df.asfreq("45s"))

输出结果:
                       s
2021-01-01 00:00:00  0.0
2021-01-01 00:00:45  NaN
2021-01-01 00:01:30  NaN
2021-01-01 00:02:15  NaN
2021-01-01 00:03:00  3.0
2021-01-01 00:03:45  NaN
2021-01-01 00:04:30  NaN

插值处理

从上述示例不难看出,升采样的结果会产生缺失值,那么就需要对缺失值进行处理,一般有以下几种处理方式:

方法 说明
pad/ffill 用前一个非缺失值去填充缺失值。
backfill/bfill 用后一个非缺失值去填充缺失值。
interpolater(‘linear’) 线性插值方法。
fillna(value) 指定一个值去替换缺失值。
# 下面使用插值方法处理 NaN 值,示例如下:
import pandas as pd
import numpy as np

#创建时间序列数据
rng = pd.date_range('1/1/2021', periods=20, freq='3D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
print(ts.resample('D').asfreq().head())
输出结果:
2021-01-01    0.555580
2021-01-02         NaN
2021-01-03         NaN
2021-01-04   -0.079324
2021-01-05         NaN
Freq: D, dtype: float64

#使用ffill处理缺失值
ts.resample('D').asfreq().ffill().head()
#插值处理,注意对比
2021-01-01    0.555580
2021-01-02    0.555580
2021-01-03    0.555580
2021-01-04   -0.079324
2021-01-05   -0.079324
Freq: D, dtype: float64



版权声明:本文为weixin_43145427原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。