从 2 列中随机选择
Get a random choice from 2 columns
如何从 2 列中随机选择?
我想从同一个 csv 文件中的 2 个不同列中随机获取 4 张卡片。我目前分别从每列中获得 4 张卡片。
我想将 2 列作为一个列使用。
谢谢
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")
旁注:没有参数replace = FALSE
的np.random.choice
可能会多次选择同一张牌,因为一个对象在选择后不会从选择池中移除被提取出来。
考虑这个解决方案:
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)
如何从 2 列中随机选择? 我想从同一个 csv 文件中的 2 个不同列中随机获取 4 张卡片。我目前分别从每列中获得 4 张卡片。 我想将 2 列作为一个列使用。
谢谢
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")
旁注:没有参数replace = FALSE
的np.random.choice
可能会多次选择同一张牌,因为一个对象在选择后不会从选择池中移除被提取出来。
考虑这个解决方案:
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)