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

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page