def generate_df(df_len, option, p_success=0.1):
'''
Generate a pandas DataFrame with one single field filled with
1s and 0s in p_success proportion and length df_len.
Input:
- df_len: int, length of the 1st dimension of the DataFrame
- option: string, determines how will the sample be generated
* random: according to a bernoully distribution with p=p_success
* fixed: failures first, and fixed proportion of successes p_success
* fixed_shuffled: fixed proportion of successes p_success, random order
- p_success: proportion of successes among total
Output:
- df: pandas Dataframe
'''
if option == 'random':
values = np.random.binomial(n=1, p=p_success, size=df_len)
elif option in ('fixed_shuffled', 'fixed'):
n_success = int(df_len*p_success)
n_fail = df_len - n_success
values = [0]*n_fail + [1]*n_success
if option == 'fixed_shuffled':
np.random.shuffle(values)
else:
raise Exception('Unknown option: {}'.format(option))
df = pd.DataFrame({'value': values})
return df
import numpy as np
import pandas as pd
input_length = 1000
# List approach:
my_list = [0 for i in range(input_length)]
# Numpy array:
my_array = np.zeros(input length)
# With Pandas:
my_table = pd.Series(0, index=range(input_length))
除了N.p.的回答。你可以这样做:
编辑:
更完整的功能:
从你所描述的,一个简单的
list
就可以了。否则,可以使用numpy.array
或pandas.DataFrame
/pandas.Series
(更像表格)。你知道吗所有这些都创建了一个零向量,然后您可以随意分配成功(1)。如果这些是遵循一些已知的分布,numpy也有方法生成跟随它们的随机向量(see here)。你知道吗
如果你真的在寻找熊猫的方法,它也可以与以前的方法相结合。也就是说,您可以将
list
或numpy.array
分配给Series
/DataFrame
的值。例如,假设您想要绘制1000个p=0.5的二项分布的随机样本:相关问题 更多 >
编程相关推荐