【问题标题】:Creating a dataframe in Python在 Python 中创建数据框
【发布时间】:2017-09-26 07:31:06
【问题描述】:

不确定如何正确表达这一点,但这里是:

在 Python 中创建包含 1 和 0 且长度由某些输入确定的单列数据框的最简单方法是什么?

例如,假设我有 1000 个样本,其中有 100 个成功(个)。零的数量将是样本大小(即 1000)减去成功。所以输出将是一个长度为 1000 的 df,其中 100 行包含 1,900 行包含 0。

【问题讨论】:

  • 是有序的还是随机的?
  • 对此没有要求——可以两者兼而有之。

标签: python


【解决方案1】:

根据您的描述,一个简单的list 就可以解决问题。否则,您可以使用numpy.arraypandas.DataFrame/pandas.Series(更像表格)。

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))

所有这些都会创建一个零向量,然后您可以随意分配成功(1)。如果这些要遵循某些已知分布,numpy 还具有生成遵循它们的随机向量的方法 (see here)。

如果你真的在寻找 pandas 的方法,它也可以与之前的方法结合使用。也就是说,您可以将listnumpy.array 分配给Series/DataFrame 的值。例如,假设您要抽取 p=0.5 的二项分布的 1000 个随机样本:

p=0.5
my_data = pd.Series(np.random.binomial(1, p, input_length))

【讨论】:

    【解决方案2】:

    除了 N.P. 的回答。你可以这样做:

    import pandas as pd
    import numpy as np
    
    def generate_df(df_len):
    
        values = np.random.binomial(n=1, p=0.1, size=df_len)
        return pd.DataFrame({'value': values})
    
    df = generate_df(1000)
    

    编辑:

    更完善的功能:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 2023-01-12
      相关资源
      最近更新 更多