1

Newbie to Python trying figure out how it all works. I'm trying to create a deck of cards and then randomly select a card (akin to dealing cards out), but I don't know how to select a single random element from a dataframe.

The code I have so far is as follows:

Hearts = ["H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ","HQ","HK","HA"]
Spades = ["S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ","SQ","SK","SA"] 
Diamonds = ["D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA"]
Clubs = ["C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ","CQ","CK","CA"]

Deck = pd.DataFrame([Hearts,Spades,Diamonds,Clubs])
print(Deck)
    0   1   2   3   4   5   6   7   8    9  10  11  12  13
0  H1  H2  H3  H4  H5  H6  H7  H8  H9  H10  HJ  HQ  HK  HA
1  S1  S2  S3  S4  S5  S6  S7  S8  S9  S10  SJ  SQ  SK  SA
2  D1  D2  D3  D4  D5  D6  D7  D8  D9  D10  DJ  DQ  DK  DA
3  C1  C2  C3  C4  C5  C6  C7  C8  C9  C10  CJ  CQ  CK  CA

I know there is a lot more involved but at this stage I would just like to be able to print one random element from the above dataframe. Hoping somebody will be able to help!

3 Answers 3

1

Create Series by DataFrame.stack and for one random value use Series.sample, last select value by Series.iat for scalar:

print(Deck.stack().sample(1).iat[0])
H9

Or use np.random.choice with flatten values by np.ravel:

print(np.random.choice(np.ravel(Deck), 1)[0])
H8
Sign up to request clarification or add additional context in comments.

Comments

0
>>> from random import choice
>>> choice(choice(Deck)
'S2'
>> choice(choice(Deck))
'D1'

Comments

0

The following will randomly select a row, and then a column.

Deck.sample(1, axis=0).sample(1, axis=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.