2017-09-26 2 views
0

확실하지 여기 제대로 표현이 있지만,에 간다 방법 :파이썬에서 dataframe 만들기

1과 0을 보유하고 파이썬에서 하나의 열 dataframe를 만들 수있는 가장 쉬운 방법이고, 길이는 몇 가지에 의해 결정된다 무엇 입력?

예를 들어, 표본 크기가 1000이고 성공률이 100입니다 (1). 0의 양은 샘플 크기 (즉, 1000)에서 성공을 뺀 것입니다. 따라서 출력은 길이가 1000 인 df이고, 100 행에는 1이 포함되고 900은 0입니다.

+0

인가? –

+0

그 요구 사항은 없습니다. 둘 다있을 수 있습니다. – user8674713

답변

0

당신이 묘사 한 것으로서, 간단한 list이 트릭을합니다. 그렇지 않은 경우 numpy.array 또는 pandas.DataFrame/pandas.Series을 사용할 수 있습니다 (더 많은 테이블 형식).

이 모든 것들은 0의 벡터를 생성합니다. 그리고 나서 여러분이 원하는대로 성공 (1)을 할당합니다. 이것들이 어떤 알려진 분포를 따르고 있다면, numpy는 그것들을 뒤 따르는 랜덤 벡터들을 생성하는 방법들을 가지고있다. (see here).

팬더의 접근 방식을 실제로 찾고 있다면 이전 유형과 결합 할 수도 있습니다. 즉, Series/DataFrame의 값에 list 또는 numpy.array을 할당 할 수 있습니다. 예를 들어, P = 0.5와 이항 분포의 1,000 무작위 샘플을 그리려는 상상 :

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

을 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 
관련 문제