복붙노트

[PYTHON] Pandas 데이터 프레임에서 yes / no 열을 1/0으로 변경하는 간단한 방법이 있습니까?

PYTHON

Pandas 데이터 프레임에서 yes / no 열을 1/0으로 변경하는 간단한 방법이 있습니까?

나는 csv 파일을 pandas 데이터 프레임으로 읽었으며, 이진 응답을 가진 열을 yes / no 문자열에서 1/0의 정수로 변환하려고합니다. 아래에서는 그러한 열 중 하나를 보여줍니다 ( "sampleDF"는 팬더 데이터 프레임 임).

In [13]: sampleDF.housing[0:10]
Out[13]:
0     no
1     no
2    yes
3     no
4     no
5     no
6     no
7     no
8    yes
9    yes
Name: housing, dtype: object

도움을 많이 받으실 수 있습니다!

해결법

  1. ==============================

    1.방법 1

    방법 1

    sample.housing.eq('yes').mul(1)
    

    방법 2

    pd.Series(np.where(sample.housing.values == 'yes', 1, 0),
              sample.index)
    

    방법 3

    sample.housing.map(dict(yes=1, no=0))
    

    방법 4

    pd.Series(map(lambda x: dict(yes=1, no=0)[x],
                  sample.housing.values.tolist()), sample.index)
    

    방법 5

    pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)
    

    모든 수익률

    0    0
    1    0
    2    1
    3    0
    4    0
    5    0
    6    0
    7    0
    8    1
    9    1
    

    타이밍 주어진 샘플

    타이밍 긴 샘플 sample = pd.DataFrame (dict (housing = np.random.choice ( 'yes', 'no'), size = 100000)))

  2. ==============================

    2.이 시도:

    이 시도:

    sampleDF['housing'] = sampleDF['housing'].map({'yes': 1, 'no': 0})
    
  3. ==============================

    3.

    # produces True/False
    sampleDF['housing'] = sampleDF['housing'] == 'yes'
    

    위의 값은 각각 1/0 인 True / False 값을 반환합니다. 부울은 합계 함수 등을 지원합니다. 실제로 1/0 값이 필요한 경우 다음을 사용할 수 있습니다.

    housing_map = {'yes': 1, 'no': 0}
    sampleDF['housing'] = sampleDF['housing'].map(housing_map)
    
  4. ==============================

    4.

    %timeit
    sampleDF['housing'] = sampleDF['housing'].apply(lambda x: 0 if x=='no' else 1)
    

    루프 당 1.84 ms ± 56.2 μs (평균 ± 표준 편차 7 회, 각각 1000 루프)

  5. ==============================

    5.일반적인 방법 :

    일반적인 방법 :

    import pandas as pd
    string_data = string_data.astype('category')
    numbers_data = string_data.cat.codes
    

    참고: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html

  6. ==============================

    6.다음을 시도하십시오.

    다음을 시도하십시오.

    sampleDF['housing'] = sampleDF['housing'].str.lower().replace({'yes': 1, 'no': 0})
    
  7. from https://stackoverflow.com/questions/40901770/is-there-a-simple-way-to-change-a-column-of-yes-no-to-1-0-in-a-pandas-dataframe by cc-by-sa and MIT license