Python 大熊猫的取样
如果我想随机采样熊猫数据帧,我可以使用Python 大熊猫的取样,python,pandas,Python,Pandas,如果我想随机采样熊猫数据帧,我可以使用 假设我随机抽取80%的行。如何自动获取未拾取的其他20%的行?正如Lagerber所解释的,可以向数据帧添加一个具有唯一索引的列,或者随机洗牌整个数据帧。对于后者 df.reindex(np.random.permutation(df.index)) 工作。(np的意思是numpy)您是用替换品取样还是不用替换品取样?如果采样而不替换:只需将具有唯一索引的列添加到数据帧。然后查看在80%中选择了哪些索引号,并使用这些索引号获得剩余的20%。或者,您可以找
假设我随机抽取80%的行。如何自动获取未拾取的其他20%的行?正如Lagerber所解释的,可以向数据帧添加一个具有唯一索引的列,或者随机洗牌整个数据帧。对于后者
df.reindex(np.random.permutation(df.index))
工作。(np的意思是numpy)您是用替换品取样还是不用替换品取样?如果采样而不替换:只需将具有唯一索引的列添加到数据帧。然后查看在80%中选择了哪些索引号,并使用这些索引号获得剩余的20%。或者,您可以找到一种方法来洗牌整个数据帧,即随机化所有行,然后将行以80:20的比例拆分,而不进行替换
>>> import pandas as pd, numpy as np
>>> df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9,10], 'b': [11,12,13,14,15,16,17,18,19,20]})
>>> df
a b
0 1 11
1 2 12
2 3 13
3 4 14
4 5 15
5 6 16
6 7 17
7 8 18
8 9 19
9 10 20
# randomly sample 5 rows
>>> sample = df.sample(5)
>>> sample
a b
7 8 18
2 3 13
4 5 15
0 1 11
3 4 14
# list comprehension to get indices not in sample's indices
>>> idxs_not_in_sample = [idx for idx in df.index if idx not in sample.index]
>>> idxs_not_in_sample
[1, 5, 6, 8, 9]
# locate the rows at the indices in the original dataframe that aren't in the sample
>>> not_sample = df.loc[idxs_not_in_sample]
>>> not_sample
a b
1 2 12
5 6 16
6 7 17
8 9 19
9 10 20