问题描述
如何将 pandas 数据框的单列转换为字符串类型?在下面的住房数据 df 中,我需要将邮政编码转换为字符串,以便在运行线性回归时,邮政编码被视为分类而不是数字.谢谢!
how do i convert a single column of a pandas dataframe to type string? in the df of housing data below i need to convert zipcode to string so that when i run linear regression, zipcode is treated as categorical and not numeric. thanks!
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
推荐答案
你需要astype:
df['zipcode'] = df.zipcode.astype(str) #df.zipcode = df.zipcode.astype(str)
<小时>
用于转换为分类:
df['zipcode'] = df.zipcode.astype('category') #df.zipcode = df.zipcode.astype('category')
另一种百家乐凯发k8的解决方案是分类:
another solution is categorical:
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