我怎样才能随机生成是和否?
how can I get a random generation of yes and no?
我怎样才能随机生成是和否?
结果存储在数据框列中。
我想随机生成是和否并将值存储在列中
但仍然没有成功......
这是我的代码,它运行良好但不会在列中存储相同的结果。
import string
import random
l1 = ["yes", "no"]
for x in range(8):
rand = random.randint(0, 1)
print(l1[rand])
mylist = ['yes', 'no']
#Since you mentioned dataframe, I'm assuming you have a file path and a dataframe
df = pd.read_excel(file_path, engine='openpyxl', index_col=None)
for i in range(8):
output = random.choice(mylist)
# Save Record in a dictionary first assuming you already have a 'Random' column in your dataframe
record_data_dict = {'Random': output}
#append dictionary to the dataframe
df = df.append(record_data_dict, ignore_index=True)
# save the updated dataframe to the excel file
df.to_excel(file_path, index=False)
您可以使用列表和 append()
来保存答案的值:
import string
import random
l1 = ["yes", "no"]
ans = [] # This for saving value of the answer
for x in range(8):
rand = random.randint(0, 1)
ans.append(l1[rand]) # Add random value to ans list
print(l1[rand])
for i in ans:
print(i)
df['Churn']= np.random.choice(['yes','no'], len(df), p=[.7,.3])
这里'churn'
是列名,df
是数据框
它解决了我的问题。
我怎样才能随机生成是和否? 结果存储在数据框列中。
我想随机生成是和否并将值存储在列中 但仍然没有成功...... 这是我的代码,它运行良好但不会在列中存储相同的结果。
import string
import random
l1 = ["yes", "no"]
for x in range(8):
rand = random.randint(0, 1)
print(l1[rand])
mylist = ['yes', 'no']
#Since you mentioned dataframe, I'm assuming you have a file path and a dataframe
df = pd.read_excel(file_path, engine='openpyxl', index_col=None)
for i in range(8):
output = random.choice(mylist)
# Save Record in a dictionary first assuming you already have a 'Random' column in your dataframe
record_data_dict = {'Random': output}
#append dictionary to the dataframe
df = df.append(record_data_dict, ignore_index=True)
# save the updated dataframe to the excel file
df.to_excel(file_path, index=False)
您可以使用列表和 append()
来保存答案的值:
import string
import random
l1 = ["yes", "no"]
ans = [] # This for saving value of the answer
for x in range(8):
rand = random.randint(0, 1)
ans.append(l1[rand]) # Add random value to ans list
print(l1[rand])
for i in ans:
print(i)
df['Churn']= np.random.choice(['yes','no'], len(df), p=[.7,.3])
这里'churn'
是列名,df
是数据框
它解决了我的问题。