我创建了一个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).
型
1条答案
按热度按时间r1wp621o1#
错误本身就说明了一切。
random.sample()
需要一个序列,比如列表/元组。在使用random
库之前,请尝试将其转换为列表:字符串
更新:
error: 'Sample larger than population or is negative.'
很可能
df['url']
包含的唯一值少于50个,这就是引发错误的原因。为了避免将来发生这种情况,让我们创建一个变量来计算唯一值:型
然后,我们在初始代码片段中使用此变量:
型
正如@juanpethes所建议的,我们还可以通过创建一个掩码来应用于主 Dataframe 来改进对结果的检查。这将为我们提供对应于所选域的dataframe中的所有行:
型