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

时间:2016-08-23 03:53:02

标签: pandas dataframe type-conversion categorical-data

如何将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

4 个答案:

答案 0 :(得分:30)

您需要astype

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')

另一个解决方案是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

答案 1 :(得分:4)

对于熊猫> = 1.0,现在有一个专用的字符串数据类型:

1)您可以使用.astype('string')将列转换为此熊猫 string数据类型

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


2),这与使用str设置熊猫对象数据类型的不同:

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)


从文档中:

'string'扩展类型解决了object-dtype的几个问题 NumPy数组:

1)您可能会意外地将字符串和非字符串的混合存储在 对象dtype数组。一个StringArray只能存储字符串。

2)对象dtype中断dtype特定的操作,例如 DataFrame.select_dtypes()。没有一种清晰的方法可以只选择文字 同时排除非文本列,但仍然是object-dtype列。

3)读取代码时,对象dtype数组的内容不太清楚 比字符串。


有关熊猫1.0的信息,请参见:
https://pandas.pydata.org/pandas-docs/version/1.0.0/whatsnew/v1.0.0.html

答案 2 :(得分:4)

针对标称数据(例如无序)的先前答案。如果有理由对序数变量强加顺序,则可以使用:

# 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

有关设置排序类别的更多详细信息,可以在pandas网站上找到:

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

答案 3 :(得分:1)

要将列转换为字符串类型(在pandas中将是 object 列本身),请使用#top-elements .large.custom-button span, #top-elements .large.custom-button span:visited { font-size: 14px; } #top-elements .social_media_top { padding: 0; }

astype

如果您想获得df.zipcode = zipcode.astype(str) 列,可以将参数Categorical传递给函数:

'category'