Randomly Choose Rows from Table - Python Pandas Read SQL2019 Community Moderator ElectionHow to randomly select an item from a list?How do you read from stdin?Why is reading lines from stdin much slower in C++ than Python?Add one row to pandas DataFrameHow to remove a key from a Python dictionary?Adding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column nameHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers
3.5% Interest Student Loan or use all of my savings on Tuition?
Book about a time-travel war fought by computers
I encountered my boss during an on-site interview at another company. Should I bring it up when seeing him next time?
How do we objectively assess if a dialogue sounds unnatural or cringy?
I've given my players a lot of magic items. Is it reasonable for me to give them harder encounters?
Where is the fallacy here?
Wardrobe above a wall with fuse boxes
PTIJ: Is all laundering forbidden during the 9 days?
Why won't the strings command stop?
How does insurance birth control work?
PTIJ: Why can't I sing about soda on certain days?
Specific Chinese carabiner QA?
What is a term for a function that when called repeatedly, has the same effect as calling once?
Misplaced tyre lever - alternatives?
What is better: yes / no radio, or simple checkbox?
Quitting employee has privileged access to critical information
School performs periodic password audits. Is my password compromised?
Being asked to review a paper in conference one has submitted to
Has Wakanda ever accepted refugees?
How can neutral atoms have exactly zero electric field when there is a difference in the positions of the charges?
It doesn't matter the side you see it
Why would the IRS ask for birth certificates or even audit a small tax return?
Giving a talk in my old university, how prominently should I tell students my salary?
GPL code private and stolen
Randomly Choose Rows from Table - Python Pandas Read SQL
2019 Community Moderator ElectionHow to randomly select an item from a list?How do you read from stdin?Why is reading lines from stdin much slower in C++ than Python?Add one row to pandas DataFrameHow to remove a key from a Python dictionary?Adding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column nameHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers
I have to choose randomly rows from a Post GRE Table within a given date-time range. They way I doing now is query the table within the date-time range and then randomly select the rows.(Please see below) This is becoming very inefficient in terms of querying as I have 10 GB of data within the range. Is there a better way to do this? Please advise
sp = pd.read_sql("SELECT * FROM table1 WHERE timestamp >= '"+sampling_start_date+"' and timestamp <= '"+sampling_end_date+"'", con)
random_subset = sp.sample(n=300)
Time Stamp format is as below
sampling_start_date = "2018-08-17 20:00:00"
python pandas random amazon-redshift
add a comment |
I have to choose randomly rows from a Post GRE Table within a given date-time range. They way I doing now is query the table within the date-time range and then randomly select the rows.(Please see below) This is becoming very inefficient in terms of querying as I have 10 GB of data within the range. Is there a better way to do this? Please advise
sp = pd.read_sql("SELECT * FROM table1 WHERE timestamp >= '"+sampling_start_date+"' and timestamp <= '"+sampling_end_date+"'", con)
random_subset = sp.sample(n=300)
Time Stamp format is as below
sampling_start_date = "2018-08-17 20:00:00"
python pandas random amazon-redshift
Is it Postgres? Anyway, perhaps you could sample the rows in your select statement, like ading something likeAND random() < 0.2
to the WHERE clause (this will select, approximately, 20% of the rows).
– amitr
19 hours ago
Thanks @amitr: Could I give some value on the number of rows?
– RajeshKumar Sugumar
15 hours ago
You're welcome. I've added a more complete answer, please take a look.
– amitr
1 hour ago
add a comment |
I have to choose randomly rows from a Post GRE Table within a given date-time range. They way I doing now is query the table within the date-time range and then randomly select the rows.(Please see below) This is becoming very inefficient in terms of querying as I have 10 GB of data within the range. Is there a better way to do this? Please advise
sp = pd.read_sql("SELECT * FROM table1 WHERE timestamp >= '"+sampling_start_date+"' and timestamp <= '"+sampling_end_date+"'", con)
random_subset = sp.sample(n=300)
Time Stamp format is as below
sampling_start_date = "2018-08-17 20:00:00"
python pandas random amazon-redshift
I have to choose randomly rows from a Post GRE Table within a given date-time range. They way I doing now is query the table within the date-time range and then randomly select the rows.(Please see below) This is becoming very inefficient in terms of querying as I have 10 GB of data within the range. Is there a better way to do this? Please advise
sp = pd.read_sql("SELECT * FROM table1 WHERE timestamp >= '"+sampling_start_date+"' and timestamp <= '"+sampling_end_date+"'", con)
random_subset = sp.sample(n=300)
Time Stamp format is as below
sampling_start_date = "2018-08-17 20:00:00"
python pandas random amazon-redshift
python pandas random amazon-redshift
asked 20 hours ago
RajeshKumar SugumarRajeshKumar Sugumar
245
245
Is it Postgres? Anyway, perhaps you could sample the rows in your select statement, like ading something likeAND random() < 0.2
to the WHERE clause (this will select, approximately, 20% of the rows).
– amitr
19 hours ago
Thanks @amitr: Could I give some value on the number of rows?
– RajeshKumar Sugumar
15 hours ago
You're welcome. I've added a more complete answer, please take a look.
– amitr
1 hour ago
add a comment |
Is it Postgres? Anyway, perhaps you could sample the rows in your select statement, like ading something likeAND random() < 0.2
to the WHERE clause (this will select, approximately, 20% of the rows).
– amitr
19 hours ago
Thanks @amitr: Could I give some value on the number of rows?
– RajeshKumar Sugumar
15 hours ago
You're welcome. I've added a more complete answer, please take a look.
– amitr
1 hour ago
Is it Postgres? Anyway, perhaps you could sample the rows in your select statement, like ading something like
AND random() < 0.2
to the WHERE clause (this will select, approximately, 20% of the rows).– amitr
19 hours ago
Is it Postgres? Anyway, perhaps you could sample the rows in your select statement, like ading something like
AND random() < 0.2
to the WHERE clause (this will select, approximately, 20% of the rows).– amitr
19 hours ago
Thanks @amitr: Could I give some value on the number of rows?
– RajeshKumar Sugumar
15 hours ago
Thanks @amitr: Could I give some value on the number of rows?
– RajeshKumar Sugumar
15 hours ago
You're welcome. I've added a more complete answer, please take a look.
– amitr
1 hour ago
You're welcome. I've added a more complete answer, please take a look.
– amitr
1 hour ago
add a comment |
1 Answer
1
active
oldest
votes
Selecting A Random Number Of Rows From A Table
Random sample of rows can be selected using a random number SQL function. In PostgreSQL, for example, it is random()
.
The number of rows selected depends on the number of rows that would be selected without the random sampling, and the sampling probability,
For example, if the table contains 5,000 rows and the sampling probability is less than 0.1, about 500 rows will be selected (10% of 5,000).
If the WHERE clause, without the random sampling, would select, say, 1,500 rows, and the sampling probability is less than 0.2, then about 300 rows will be selected (20% of 1,500).
Notice that using this method you cannot guarantee the exact number of selected rows (that's the nature of probability...), so in order to get a number of rows close to what you desire you will have to appropriately choose the probability.
Also notice that if you want to repeat this process and get the same results every time, you'll have to seed the random number generator with the same value. You can do that with the setseed()
function:
SELECT setseed(.123);
Last thing, the random()
function exists in PostgeSQL. Other database engines might use a different name for that function (in MySQL and SQL Server, for example, I believe it is rand()
).
See the following select statements for some examples.
-- 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
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55021558%2frandomly-choose-rows-from-table-python-pandas-read-sql%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Selecting A Random Number Of Rows From A Table
Random sample of rows can be selected using a random number SQL function. In PostgreSQL, for example, it is random()
.
The number of rows selected depends on the number of rows that would be selected without the random sampling, and the sampling probability,
For example, if the table contains 5,000 rows and the sampling probability is less than 0.1, about 500 rows will be selected (10% of 5,000).
If the WHERE clause, without the random sampling, would select, say, 1,500 rows, and the sampling probability is less than 0.2, then about 300 rows will be selected (20% of 1,500).
Notice that using this method you cannot guarantee the exact number of selected rows (that's the nature of probability...), so in order to get a number of rows close to what you desire you will have to appropriately choose the probability.
Also notice that if you want to repeat this process and get the same results every time, you'll have to seed the random number generator with the same value. You can do that with the setseed()
function:
SELECT setseed(.123);
Last thing, the random()
function exists in PostgeSQL. Other database engines might use a different name for that function (in MySQL and SQL Server, for example, I believe it is rand()
).
See the following select statements for some examples.
-- 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
add a comment |
Selecting A Random Number Of Rows From A Table
Random sample of rows can be selected using a random number SQL function. In PostgreSQL, for example, it is random()
.
The number of rows selected depends on the number of rows that would be selected without the random sampling, and the sampling probability,
For example, if the table contains 5,000 rows and the sampling probability is less than 0.1, about 500 rows will be selected (10% of 5,000).
If the WHERE clause, without the random sampling, would select, say, 1,500 rows, and the sampling probability is less than 0.2, then about 300 rows will be selected (20% of 1,500).
Notice that using this method you cannot guarantee the exact number of selected rows (that's the nature of probability...), so in order to get a number of rows close to what you desire you will have to appropriately choose the probability.
Also notice that if you want to repeat this process and get the same results every time, you'll have to seed the random number generator with the same value. You can do that with the setseed()
function:
SELECT setseed(.123);
Last thing, the random()
function exists in PostgeSQL. Other database engines might use a different name for that function (in MySQL and SQL Server, for example, I believe it is rand()
).
See the following select statements for some examples.
-- 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
add a comment |
Selecting A Random Number Of Rows From A Table
Random sample of rows can be selected using a random number SQL function. In PostgreSQL, for example, it is random()
.
The number of rows selected depends on the number of rows that would be selected without the random sampling, and the sampling probability,
For example, if the table contains 5,000 rows and the sampling probability is less than 0.1, about 500 rows will be selected (10% of 5,000).
If the WHERE clause, without the random sampling, would select, say, 1,500 rows, and the sampling probability is less than 0.2, then about 300 rows will be selected (20% of 1,500).
Notice that using this method you cannot guarantee the exact number of selected rows (that's the nature of probability...), so in order to get a number of rows close to what you desire you will have to appropriately choose the probability.
Also notice that if you want to repeat this process and get the same results every time, you'll have to seed the random number generator with the same value. You can do that with the setseed()
function:
SELECT setseed(.123);
Last thing, the random()
function exists in PostgeSQL. Other database engines might use a different name for that function (in MySQL and SQL Server, for example, I believe it is rand()
).
See the following select statements for some examples.
-- 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
Selecting A Random Number Of Rows From A Table
Random sample of rows can be selected using a random number SQL function. In PostgreSQL, for example, it is random()
.
The number of rows selected depends on the number of rows that would be selected without the random sampling, and the sampling probability,
For example, if the table contains 5,000 rows and the sampling probability is less than 0.1, about 500 rows will be selected (10% of 5,000).
If the WHERE clause, without the random sampling, would select, say, 1,500 rows, and the sampling probability is less than 0.2, then about 300 rows will be selected (20% of 1,500).
Notice that using this method you cannot guarantee the exact number of selected rows (that's the nature of probability...), so in order to get a number of rows close to what you desire you will have to appropriately choose the probability.
Also notice that if you want to repeat this process and get the same results every time, you'll have to seed the random number generator with the same value. You can do that with the setseed()
function:
SELECT setseed(.123);
Last thing, the random()
function exists in PostgeSQL. Other database engines might use a different name for that function (in MySQL and SQL Server, for example, I believe it is rand()
).
See the following select statements for some examples.
-- 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
answered 1 hour ago
amitramitr
1187
1187
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55021558%2frandomly-choose-rows-from-table-python-pandas-read-sql%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Is it Postgres? Anyway, perhaps you could sample the rows in your select statement, like ading something like
AND random() < 0.2
to the WHERE clause (this will select, approximately, 20% of the rows).– amitr
19 hours ago
Thanks @amitr: Could I give some value on the number of rows?
– RajeshKumar Sugumar
15 hours ago
You're welcome. I've added a more complete answer, please take a look.
– amitr
1 hour ago