我有一组数据,包含以下列:
['symboling', 'Company', 'fueltype', 'aspiration', 'doornumber', 'carbody', 'drivewheel', 'enginelocation', 'carlength', 'carwidth', 'curbweight', 'enginetype', 'cylindernumber', 'enginesize', 'fuelsystem', 'horsepower', 'price', 'total_mpg']
目标是预测汽车的价格。现在价格数据是连续的。我在想如何将其转换,以便我可以使用分类模型。
经过搜索,我发现可以通过定义范围来实现,但我无法理解。请帮助我。
回答:
假设我们有一个包含两个连续列的DataFrame,命名为x1
和x2
:
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsx1 = np.random.rand(100)x2 = np.random.rand(100)df = pd.DataFrame({"x1":x1,"x2":x2})df.head()# x1 x2#0 0.049202 0.131046#1 0.606525 0.756687#2 0.910932 0.944692#3 0.904655 0.439637#4 0.565204 0.418432# 绘制值sns.scatterplot(x=range(100),y=df["x1"])sns.scatterplot(x=range(100),y=df["x2"])
然后我们可以这样创建一些区间:
x1_cat = pd.cut(df['x1'], bins=[0.,0.2,0.4,0.6,0.8,np.inf], labels=[0,1,2,3,4])x2_cat = pd.cut(df['x2'], bins=[0.,0.2,0.4,0.6,0.8,np.inf], labels=[0,1,2,3,4])df_cat = pd.concat([x1_cat,x2_cat],axis=1)df_cat.head()# x1 x2#0 0 0#1 3 3#2 4 4#3 4 2#4 2 2# 绘制值sns.scatterplot(x=range(100),y=df_cat["x1"])sns.scatterplot(x=range(100),y=df_cat["x2"])