如何修复pandas错误'人口必须是一个序列,对于dicts或set,使用sorted(d),

yftpprvb  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(277)

我创建了一个dataframe df来保存我的浏览器历史记录。An example of one of the rows is given here. Please look at it:
问题是我想使用random.sample()函数来过滤数据,以保存50个不安全的域(例如:Netflix)。然而,当我运行代码时,我得到了错误:Population must be a sequence. For dicts or sets, use sorted(d).
代码:

import random

# Manual inspection, picking 50 random domains which were insecure
random.sample(df\[df\["is_secure"\] == False\].domain.unique(), 50)

字符串
错误代码:

Population must be a sequence.  For dicts or sets, use sorted(d).

r1wp621o

r1wp621o1#

错误本身就说明了一切。random.sample()需要一个序列,比如列表/元组。在使用random库之前,请尝试将其转换为列表:

random_domains = random.sample(df[df['is_secure'] == False].domain.unique().tolist(), 50)

字符串
更新:error: 'Sample larger than population or is negative.'
很可能df['url']包含的唯一值少于50个,这就是引发错误的原因。为了避免将来发生这种情况,让我们创建一个变量来计算唯一值:

num_sample = len(set(df['url']))


然后,我们在初始代码片段中使用此变量:

random_domains = random.sample(df[df['is_secure'] == False].domain.unique().tolist(), num_sample)


正如@juanpethes所建议的,我们还可以通过创建一个掩码来应用于主 Dataframe 来改进对结果的检查。这将为我们提供对应于所选域的dataframe中的所有行:

df_random_domains = df[df['url'].isin(random_domains)]
print(df_random_domains)

相关问题