How can I get a random choice from 2 columns? I want to randomly get 4 cards from 2 different columns in the same csv file. I currently get 4 cards from each column separately. I would like to use from 2 columns as one.
Thanks
import pandas as pd
import numpy as np
import random
df = pd.read_csv('test.csv')
df.drop(['q','w'],inplace=True, axis=1)
n = 0
z = n 10
df=df.iloc[n:z]
g = df['a']
j = df['b']
#p = g j
for i in range(5):
cards_1 = np.random.choice(g, 4)
print(cards_1)
print("\n")
for ii in range(5):
cards_2 = np.random.choice(j, 4)
print(cards_2, sep = "\n")
CodePudding user response:
Side Note: np.random.choice
without the parameter replace = FALSE
might pick a single card multiple times as an object is not removed from the choice pool after it is extracted.
Consider this solution:
import pandas as pd
import numpy as np
# Dont worry about this. this is only to get some sample data
df = pd.DataFrame(np.transpose(np.array(
[[7,8,9,10, "j", "q", "k", "a"],
[7,8,9,10, "j", "q", "k", "a"],
[7,8,9,10, "j", "q", "k", "a"]])),
columns=['a', 'b', 'c'])
# end of data
# Choose two column names without replacement (dont pick same column twice or more)
random_colnames = np.random.choice(df.columns,2, replace = False)
# Custom colnames could be
#custom_colnames = ['a', 'b']
#drawn_cards = []
for col in random_colnames:
# pick elements from column with replacement
# and extend them to the list of already drawn cards
for _ in range(5):
# add replace = False if you do not want the same cardd picked more than once
draw = np.random.choice(df[col],4)
#drawn_cards.extend(draw)
print(draw)
# Print for showcase purpose
# print(drawn_cards)