programing

pandas 데이터프레임 열 유형을 문자열 또는 범주형으로 변환

cafebook 2023. 10. 20. 14:21
반응형

pandas 데이터프레임 열 유형을 문자열 또는 범주형으로 변환

팬더 데이터 프레임의 한 열을 입력 문자열로 변환하려면 어떻게 해야 합니까?아래 주택 데이터의 df에서는 선형 회귀를 실행할 때 zipcode가 숫자가 아닌 범주형으로 처리되도록 zipcode를 문자열로 변환해야 합니다.감사합니다!

df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot  zipcode
722         3.25         4     2.0         4670     51836    98005
2680        0.75         2     1.0         1440      3700    98107
14554       2.50         4     2.0         3180      9603    98155
17384       1.50         2     3.0         1430      1650    98125
18754       1.00         2     1.0         1130      2640    98109

필요한 항목:

df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)

로 변환하기 위해categorical:

df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')

또 다른 해결책은 다음과 같습니다.

df['zipcode'] = pd.Categorical(df.zipcode)

데이터가 포함된 표본:

import pandas as pd

df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot  zipcode
722         3.25         4     2.0         4670     51836    98005
2680        0.75         2     1.0         1440      3700    98107
14554       2.50         4     2.0         3180      9603    98155
17384       1.50         2     3.0         1430      1650    98125
18754       1.00         2     1.0         1130      2640    98109

print (df.dtypes)
bathrooms      float64
bedrooms         int64
floors         float64
sqft_living      int64
sqft_lot         int64
zipcode          int64
dtype: object

df['zipcode'] = df.zipcode.astype('category')

print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot zipcode
722         3.25         4     2.0         4670     51836   98005
2680        0.75         2     1.0         1440      3700   98107
14554       2.50         4     2.0         3180      9603   98155
17384       1.50         2     3.0         1430      1650   98125
18754       1.00         2     1.0         1130      2640   98109

print (df.dtypes)
bathrooms       float64
bedrooms          int64
floors          float64
sqft_living       int64
sqft_lot          int64
zipcode        category
dtype: object

panda >= 1.0에서는 이제 전용 문자열 데이터 유형이 있습니다.

1).astype('string')을 사용하여 열을 이 팬더 문자열 데이터 유형으로 변환할 수 있습니다.

df['zipcode'] = df['zipcode'].astype('string')

2)이것은 사용하는 것과 다릅니다.strPandas 개체 데이터 유형을 설정합니다.

df['zipcode'] = df['zipcode'].astype(str)

3)범주형 데이터 유형으로 변경하려면 다음을 사용합니다.

df['zipcode'] = df['zipcode'].astype('category')

데이터 프레임의 정보를 살펴보면 다음과 같은 데이터 유형의 차이를 알 수 있습니다.

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

'string' 확장자 유형은 object-dtype NumPy 배열과 관련된 몇 가지 문제를 해결합니다.

  1. 실수로 문자열과 비 문자열의 혼합을 개체 및 유형 배열에 저장할 수 있습니다.StringArray는 문자열만 저장할 수 있습니다.

  2. objecttype은 DataFrame과 같은 분산된 유형별 작업입니다.select_dtype텍스트가 아닌 개체-dtype 열을 제외하고 텍스트만 선택할 수 있는 명확한 방법은 없습니다.

  3. 코드를 읽을 때 개체 dtype 배열의 내용이 문자열보다 덜 명확합니다.

새 문자열 데이터 유형 작업에 대한 자세한 내용은 https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html 에서 확인할 수 있습니다.

사전 답변은 공칭 데이터(예: 순서 미정)에 초점을 맞춥니다.순서형 변수에 순서를 부여하는 이유가 있는 경우 다음을 사용합니다.

# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')

# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']

# Setup the ordering
df.zipcode_ordered.cat.set_categories(
    new_categories = [90211, 90210], ordered = True, inplace = True
)

# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
#  zipcode_category zipcode_ordered  zipcode_ordered_id
#            90210           90210                   1
#            90211           90211                   0

순서 범주 설정에 대한 자세한 내용은 판다 웹사이트에서 확인할 수 있습니다.

https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order

열을 문자열 유형으로 변환하려면(판다의 개체 열이 됨) 다음을 사용합니다.astype:

df.zipcode = zipcode.astype(str)

당신이 원하는 것은.Categorical열, 매개변수를 전달할 수 있습니다.'category'다음과 같은 기능을 수행합니다.

df.zipcode = zipcode.astype('category')

언급URL : https://stackoverflow.com/questions/39092067/pandas-dataframe-convert-column-type-to-string-or-categorical

반응형