Pandas随机取数
本文记录的是如何使用Python、pandas、numpy、scikit-learn来实现随机打乱、抽取和切割数据。主要的方法包含:
- sample
- shuffle
- np.random.permutation
- train_test_split
导入数据
In [1]:
1 | import pandas as pd |
内置数据
采用的是plotly库中内置的一份消费数据集:
In [2]:
1 | df = px.data.tips() |
基本信息
In [3]:
1 | df.shape |
Out[3]:
1 | (244, 7) |
In [4]:
1 | columns = df.columns |
Out[4]:
1 | Index(['total_bill', 'tip', 'sex', 'smoker', 'day', 'time', 'size'], dtype='object') |
sample实现
行方向
In [5]:
随机抽取一行记录:
1 | df.sample() |
随机抽取多行数据:
通过参数frac实现按照比例随机抽样:
1 | df.sample(frac=0.05) |
列方向
主要是选择不同数量或者比例的属性;整体的行数量是不变的
In [8]:
1 | df.sample(3, axis=1) # 在列属性上抽取 |
shuffle实现
scikit-Learn的shuffle
In [9]:
1 | from sklearn.utils import shuffle |
In [10]:
1 | shuffle(df) # 打乱数据 |
random模块的shuffle
In [11]:
1 | = l df))) # 原始的长度作为索引 |
Out[11]:
1 | [0, 1, 2, 3, 4] |
In [12]:
1 | random.shuffle(length) # 打乱索引 |
In [13]:
1 | length[:5] |
Out[13]:
1 | [136, 35, 207, 127, 29] # 打乱后的结果 |
In [14]:
1 | df.iloc[length] # 通过打乱后的索引获取数据 |
numpy实现
In [15]:
1 | # 先打乱每个索引 |
Out[15]:
1 | array([223, 98, 238, 17, 101, 26, 122, 212, 27, 79, 210, 147, 176, |
In [16]:
1 | # 通过打乱后的索引来选择数据 |
train_test_split实现
1 | from sklearn.model_selection import train_test_split |
In [18]:
第一份数据是80%的:
1 | data[0] # 80%的数据 |
剩余的20%的数据: