[英]Random rows based on unique values
I want to get 2 random but distinct person IDs from a DF and put it into another DF我想从 DF 中获取 2 个随机但不同的人员 ID,并将其放入另一个 DF
Person_id Person_id | post邮政 | active积极的 |
---|---|---|
567 567 | yes是的 | inactive不活跃 |
678 678 | yes是的 | active积极的 |
567 567 | no不 | inactive不活跃 |
689 689 | yes是的 | active积极的 |
680 680 | yes是的 | inactive不活跃 |
689 689 | no不 | active积极的 |
df['person_id'].sample(n=100, random_state=1)
This code is NOT getting the unique person_id values and only putting that column in a df.此代码未获取唯一的 person_id 值,仅将该列放在 df 中。 I need to get a number of that specific column's unique values and put it into a df with all other columns as well.我需要获取该特定列的许多唯一值,并将其与所有其他列一起放入 df 中。
df.person_id.sample(n=100, random_state=1).groupby('person_id')
I tried this as well but it creates a weird object我也试过这个,但它创建了一个奇怪的 object
Any tips?有小费吗?
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']})
To select two random unique person ids:到 select 两个随机的唯一人员 ID:
selected = df['person_id'].drop_duplicates().sample(n=2)
To create data frame with all rows for selected person ids:要为选定的人员 ID 创建包含所有行的数据框:
df[df['person_id'].isin(selected)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.