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










1















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"









share|improve this question






















  • 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















1















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"









share|improve this question






















  • 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













1












1








1








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"









share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










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 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

















  • 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
















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












1 Answer
1






active

oldest

votes


















0














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





share|improve this answer






















    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
    );



    );













    draft saved

    draft discarded


















    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









    0














    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





    share|improve this answer



























      0














      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





      share|improve this answer

























        0












        0








        0







        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





        share|improve this answer













        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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 1 hour ago









        amitramitr

        1187




        1187





























            draft saved

            draft discarded
















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme