gpt4 book ai didi

python - 从表中随机选择行 - Python Pandas 读取 SQL

转载 作者:太空宇宙 更新时间:2023-11-03 21:11:45 24 4
gpt4 key购买 nike

我必须在给定的日期时间范围内从 GRE 后表中随机选择行。我现在做的方式是在日期时间范围内查询表,然后随机选择行。(请参见下文)这在查询方面变得非常低效,因为我在该范围内有 10 GB 的数据。有一个更好的方法吗?请指教

sp = pd.read_sql("SELECT * FROM table1 WHERE timestamp >= '"+sampling_start_date+"' and timestamp <= '"+sampling_end_date+"'", con)

random_subset = sp.sample(n=300)

时间戳格式如下

sampling_start_date = "2018-08-17 20:00:00"

最佳答案

从表中选择随机数量的行

可以使用随机数 SQL 函数选择行的随机样本。例如,在 PostgreSQL 中,它是random()

选择的行数取决于不进行随机采样时选择的行数以及采样概率,

例如,如果表包含 5,000 行,并且采样概率小于 0.1,则将选择大约 500 行(5,000 行的 10%)。

如果 WHERE 子句在没有随机采样的情况下选择 1,500 行,并且采样概率小于 0.2,则将选择大约 300 行(1,500 行的 20%)。

请注意,使用此方法您无法保证所选行的确切数量(这就是概率的本质......),因此为了获得接近您想要的行数,您必须适当选择概率.

另请注意,如果您想重复此过程并每次都获得相同的结果,则必须使用相同的值作为随机数生成器的种子。您可以使用 setseed() 函数来做到这一点:

SELECT setseed(.123);

最后一件事,PostgeSQL 中存在 random() 函数。其他数据库引擎可能会为该函数使用不同的名称(例如,在 MySQL 和 SQL Server 中,我认为它是 rand())。

请参阅以下 select 语句的一些示例。

-- all rows
select count(*) from my_table;
-- 5264

-- should get about half of all rows
select count(*) from my_table where random() < 0.5;
-- 2734

-- should get about 10% of all rows
select count(*) from my_table where random() < 0.1;
-- 513

-- all rows matching some criteria
select count(*) from my_table where id > 100000 and id < 400000;
-- 3023

-- about half of the rows matching the above criteria
select count(*) from my_table where id > 100000 and id < 400000 and random() < 0.5;
-- 1527

-- about 10% of the rows matching the above criteria
select count(*) from my_table where id > 100000 and id < 400000 and random() < 0.1;
-- 283

关于python - 从表中随机选择行 - Python Pandas 读取 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55021558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com