pandas 将某一列转换为字符类型,pandas dataframe将列类型转换为字符串或分类

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

解决方案

You need astype:

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

#df.zipcode = df.zipcode.astype(str)

For converting to categorical:

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

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

Another solution is Categorical:

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

Sample with data:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值