![](/img/trans.png)
[英]Pandas dataframe, select n random rows based on number of unique values
[英]Random rows based on unique values
我想从 DF 中获取 2 个随机但不同的人员 ID,并将其放入另一个 DF
Person_id | 邮政 | 积极的 |
---|---|---|
567 | 是的 | 不活跃 |
678 | 是的 | 积极的 |
567 | 不 | 不活跃 |
689 | 是的 | 积极的 |
680 | 是的 | 不活跃 |
689 | 不 | 积极的 |
df['person_id'].sample(n=100, random_state=1)
此代码未获取唯一的 person_id 值,仅将该列放在 df 中。 我需要获取该特定列的许多唯一值,并将其与所有其他列一起放入 df 中。
df.person_id.sample(n=100, random_state=1).groupby('person_id')
我也试过这个,但它创建了一个奇怪的 object
有小费吗?
df = pd.DataFrame({'person_id': [567, 678, 567, 689, 680, 689],
'post': ['yes', 'yes', 'no', 'yes', 'yes', 'no'],
'active': ['inactive', 'active', 'inactive', 'active', 'inactive', 'active']})
到 select 两个随机的唯一人员 ID:
selected = df['person_id'].drop_duplicates().sample(n=2)
要为选定的人员 ID 创建包含所有行的数据框:
df[df['person_id'].isin(selected)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.