Skip to content
Advertisement

pandas: apply random.shuffle() to list column

I have a dataframe as follows,

JavaScript

I would like to shuffle the words in each row using random.shuffle(),(e.g the new first row will be ‘nice is weather the’ ),so I have done the following,

JavaScript

and tried to map or apply shuffle() function but it returns None.

JavaScript

or

JavaScript

I am not sure what I am doing wrong here. and then finally I would like to join the shuffled words in the list to get a string per row,

JavaScript

Advertisement

Answer

This does the job.

JavaScript

The thing with np.random.shuffle is that it doesn’t return any output. So you need to store the list you want to shuffle in a vraible first. Then if you apply np.random.shuffle on it, the original variable itself would be shuffled.

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