Shuffle DataFrame rows

I have the following DataFrame:

        Col1  Col2  Col3  Type
    0      1     2     3     1
    1      4     5     6     1
    ...
    20     7     8     9     2
    21    10    11    12     2
    ...
    45    13    14    15     3
    46    16    17    18     3
    ...

The DataFrame is read from a csv file. All rows which have Type 1 are on top, followed by the rows with Type 2, followed by the rows with Type 3, etc.

I would like to shuffle the DataFrame's rows, so that all Type's are mixed. A possible result could be:

        Col1  Col2  Col3  Type
    0      7     8     9     2
    1     13    14    15     3
    ...
    20     1     2     3     1
    21    10    11    12     2
    ...
    45     4     5     6     1
    46    16    17    18     3
    ...

As can be seen from the result, the order of the rows is shuffled, but the columns remain the same. I don't know if I am explaining this clearly. Let me know if I don't.

How can I achieve this?

The more idiomatic way to do this with pandas is to use the .sample method of your dataframe, i.e.

    df.sample(frac=1)

The frac keyword argument specifies the fraction of rows to return in the random sample, so frac=1 means return all rows (in random order).

Note: If you wish to shuffle your dataframe in-place and reset the index, you could do e.g.

    df = df.sample(frac=1).reset_index(drop=True)

_Here, specifyingdrop=True prevents .reset_index from creating a column containing the old index entries._

From: stackoverflow.com/q/29576430