在Python中的pandas DataFrame中更改值

问题描述 投票:0回答:1

我有一个已加载到熊猫DataFrame中的数据集。当我打印data.head()时,它看起来像这样。

G1  G2  G3  absences  failures  studytime romantic internet
0   5   6   6         6         0          2       no       no
1   5   5   6         4         0          2       no      yes
2   7   8  10        10         3          2       no      yes
3  15  14  15         2         0          3      yes      yes
4   6  10  10         4         0          2       no       no

我正在尝试创建线性回归模型,并希望将romanticinternet列中的yes和no转换为1和0。

我使用的代码:

df['romantic'].replace('yes', 0)
df['romantic'].replace('no', 1)
df['internet'].replace('yes', 0)
df['internet'].replace('no', 1)

没有用:(它也没有显示任何类型的错误。

我试图用data = df[["G1", "G2", "G3", "absences", "failures", "studytime", "romantic", "internet"]]建立线性模型,它显示:

ValueError: could not convert string to float: 'yes'

尽管我以为我转换了它们。请帮助,谢谢...

python pandas dataframe machine-learning linear-regression
1个回答
0
投票

如果要用0代替所有'是',而用1代替所有'否':

df.replace({'yes': 0, 'no': 1})
© www.soinside.com 2019 - 2024. All rights reserved.