从列表列中随机 select 值,以便列表中的所有元素都被 selected
Randomly select values from a list column so that all elements across lists are selected
说,我有一个 pandas 数据框,其中包含一个列表列 'event_ids'
code canceled event_ids
xxx [1.0] [107385, 128281, 133015]
xxS [0.0] [108664, 110515, 113556]
ssD [1.0] [134798, 133499, 125396, 114298, 133915]
cvS [0.0] [107611]
eeS [5.0] [113472, 115236, 108586, 128043, 114106, 10796...
544W [44.0] [107650, 128014, 127763, 118036, 116247, 12802.
如何select k 行足够随机,以便 'event_ids' 中的所有元素都在样本中表示?我的意思是样本中的事件词汇应该与总体中的事件词汇相同。 'sufficiently' 随机我的意思是如果某种重要性抽样是可能的,那么最初样本是随机的,并根据某些条件添加或拒绝。
不清楚您是否要 select events_ids 列表中的每个元素,或者每个列表是否应被视为唯一元素。
在后一种情况下,这可以工作(不确定性能!)
鉴于此数据集:
x = np.random.randint(1,100, 5000)
y = [np.random.choice(['A','B','C','D','E','F']) for i in range(5000)]
df = pd.DataFrame({'x':x,'y':y})
df.head()
Output:
x y
0 42 A
1 88 B
2 80 A
3 69 B
4 72 B
第 'x' 列中有 99 个唯一值。您想要采样,以便 df['x'] 中的每个唯一值都在获得的样本中。
idxs = []
for i in df.x.unique():
idxs.extend(np.random.choice(df.loc[df['x']==i].index, size=1))
sample = df.loc[idxs]
len(sample.x.unique())
Output:
99
您可以更改首选大小以获得样本中的更多值。
如果您想要 events_ids 中每个列表中的每个唯一元素,那么您可以使用 explode 然后使用相同的代码。
df
Out:
x y z
0 84 D [14805, 9243, 14838, 10204]
1 70 D [6901, 1117, 3918, 8607, 1912]
2 7 F [9853, 12519, 13011, 13279]
3 45 A [6344, 14646, 9633, 4517, 9432, 11187]
4 41 A [1104, 10318, 12531, 9443, 8347]
df = df.explode('z').reset_index()
df.head()
Out:
x y z
0 13 D 1876
1 13 D 2437
2 13 D 2681
3 13 D 1748
4 37 E 10155
说,我有一个 pandas 数据框,其中包含一个列表列 'event_ids'
code canceled event_ids
xxx [1.0] [107385, 128281, 133015]
xxS [0.0] [108664, 110515, 113556]
ssD [1.0] [134798, 133499, 125396, 114298, 133915]
cvS [0.0] [107611]
eeS [5.0] [113472, 115236, 108586, 128043, 114106, 10796...
544W [44.0] [107650, 128014, 127763, 118036, 116247, 12802.
如何select k 行足够随机,以便 'event_ids' 中的所有元素都在样本中表示?我的意思是样本中的事件词汇应该与总体中的事件词汇相同。 'sufficiently' 随机我的意思是如果某种重要性抽样是可能的,那么最初样本是随机的,并根据某些条件添加或拒绝。
不清楚您是否要 select events_ids 列表中的每个元素,或者每个列表是否应被视为唯一元素。 在后一种情况下,这可以工作(不确定性能!)
鉴于此数据集:
x = np.random.randint(1,100, 5000)
y = [np.random.choice(['A','B','C','D','E','F']) for i in range(5000)]
df = pd.DataFrame({'x':x,'y':y})
df.head()
Output:
x y
0 42 A
1 88 B
2 80 A
3 69 B
4 72 B
第 'x' 列中有 99 个唯一值。您想要采样,以便 df['x'] 中的每个唯一值都在获得的样本中。
idxs = []
for i in df.x.unique():
idxs.extend(np.random.choice(df.loc[df['x']==i].index, size=1))
sample = df.loc[idxs]
len(sample.x.unique())
Output:
99
您可以更改首选大小以获得样本中的更多值。
如果您想要 events_ids 中每个列表中的每个唯一元素,那么您可以使用 explode 然后使用相同的代码。
df
Out:
x y z
0 84 D [14805, 9243, 14838, 10204]
1 70 D [6901, 1117, 3918, 8607, 1912]
2 7 F [9853, 12519, 13011, 13279]
3 45 A [6344, 14646, 9633, 4517, 9432, 11187]
4 41 A [1104, 10318, 12531, 9443, 8347]
df = df.explode('z').reset_index()
df.head()
Out:
x y z
0 13 D 1876
1 13 D 2437
2 13 D 2681
3 13 D 1748
4 37 E 10155