user11509999
user11509999

Reputation:

How to create a DataFrame with random sample from list?

I have a list named list1

  list1 = ['Banana','Apple','Pear','Strawberry','Muskmelon','Apricot','Peach','Plum','Cherry','Blackberry','Raspberry','Cranberry','Grapes','Greenapple','Kiwi','Watermelon','Orange','Lychee','Custardapples','Jackfruit','Pineapple','Mango']

I want to form a df with specific columns and random data from list1

Eg:

        a          b       c            d            e         f
   0  Banana    Orange   Lychee     Custardapples Jackfruit  Pineapple
   1   Apple    Pear   Strawberry   Muskmelon    Apricot    Peach
   2  Raspberry Cherry  Plum           Kiwi        Mango   Blackberry

A structure something like this but with random data from list1? There can't be any duplicate/repeated values present.

Upvotes: 2

Views: 73

Answers (1)

Darkonaut
Darkonaut

Reputation: 21654

If every item from the list can end up everywhere in the DataFrame you could write:

pd.DataFrame(np.random.choice(list1, 3*6, replace=False).reshape(3, 6), columns=list("abcdef"))

Out: 
        a           b           c          d              e          f
0  Lychee       Peach     Apricot       Pear           Plum     Grapes
1  Cherry   Jackfruit  Blackberry  Cranberry           Kiwi      Apple
2  Orange  Greenapple  Watermelon     Banana  Custardapples  Raspberry

The replace-parameter in np.random.choice() is True by default, so for unique values you need to set it to False.

Upvotes: 4

Related Questions