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

标签 python pandas random amazon-redshift

我必须在给定的日期时间范围内从 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/

相关文章:

python - 从 Pandas 数据框中选择特定的索引、列对

python - 优化 Python 代码以进行数据库访问

python - 在 Intellij 中使用 pipenv 运行 Django 测试

Python/Selenium/Chromedriver : the script opens just a blank Google Chrome page

python - Pandas 性能问题 - 需要帮助来优化

mysql - 优化 MySQL 的 LEFT OUTER JOIN 中的 ORDER BY RAND() 函数

python - 有什么方法可以在for循环中保存多个绘图而不用Python覆盖?

python - Python:matplotlib/pandas-将数据框绘制为子图中的表

javascript - Javascript 中的无偏随机范围生成器

python:具有概率的随机样本