Skip to content
Advertisement

Shuffle DataFrame rows

I have the following DataFrame:

JavaScript

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 order of the DataFrame’s rows so that all Type‘s are mixed. A possible result could be:

JavaScript

How can I achieve this?

Advertisement

Answer

The idiomatic way to do this with Pandas is to use the .sample method of your data frame to sample all rows without replacement:

JavaScript

The frac keyword argument specifies the fraction of rows to return in the random sample, so frac=1 means to 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.

JavaScript

Here, specifying drop=True prevents .reset_index from creating a column containing the old index entries.

Follow-up note: Although it may not look like the above operation is in-place, python/pandas is smart enough not to do another malloc for the shuffled object. That is, even though the reference object has changed (by which I mean id(df_old) is not the same as id(df_new)), the underlying C object is still the same. To show that this is indeed the case, you could run a simple memory profiler:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement