
[英]How can I select a sequence of random rows from a pandas DataFrame?
[英]How can I select a random sequence of n rows for each group in a pandas data frame?
假设我有以下数据框:
raw_data = {
'subject_id': ['1', '1', '1', '1', '2','2','2','2','2'],
'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Brian','Bob','Bill','Brenda','Brett']}
df = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name'])
我如何 select 为每个subject_id
从df
随机行的 n 行序列? 例如,如果我想要每个subject_id
的 2 个随机行序列,则可能的 output 将是:
subject_id first_name
1 Amy
1 Allen
2 Brenda
2 Brett
似乎与这个问题最相似的帖子似乎是:
select 来自 pandas dataframe 的随机行序列
但是,这似乎没有考虑到我需要做的分组。
样品后的一些工作
s = df.groupby('subject_id')['subject_id'].sample(n=2)
idx = s.sort_index().drop_duplicates().index
s = df.loc[idx.union(idx+1)]
Out[53]:
subject_id first_name
2 1 Allen
3 1 Alice
4 2 Brian
5 2 Bob
您可以尝试以下方法:
import random
import pandas as pd
raw_data = {
'subject_id': ['1', '1', '1', '1', '2','2','2','2','2'],
'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Brian','Bob','Bill','Brenda','Brett']}
df = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name'])
def f(g):
k = random.randrange(len(g)-1)
return g.iloc[k:k+2]
sample = df.groupby('subject_id').apply(f).reset_index(level=0, drop=True)
print(sample)
它给:
subject_id first_name
0 1 Alex
1 1 Amy
5 2 Bob
6 2 Bill
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.