如何将数据帧的单个列转换为字符串类型?在下面住房数据的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
与熊猫一起>;=1.0现在有一个专用的字符串数据类型:
1)您可以使用.astype('string')将列转换为该字符串数据类型:
2)这与使用
str
设置对象数据类型不同:3)要更改为分类数据类型请使用:
当您查看数据帧的信息时,可以看到数据类型的这种差异:
从文档中:
有关使用新字符串数据类型的更多信息,请参见: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html
您需要^{} :
要转换为
categorical
,请执行以下操作:另一个解决方案是^{} :
数据样本:
先前的回答侧重于名义数据(例如无序数据)。如果有理由对顺序变量施加顺序,则可以使用:
有关设置有序类别的更多详细信息,请访问pandas网站:
https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order
相关问题 更多 >
编程相关推荐