首页 > 解决方案 > 在 Python 中更改 pandas DataFrame 中的值

问题描述

我有一个已加载到 pandas 的数据集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列中的 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'

即使我认为我改变了他们。请帮忙,谢谢...

标签: pythonpandasdataframemachine-learninglinear-regression

解决方案


要转换您感兴趣的两个列,请运行:

df.romantic = (df.romantic == 'yes').astype(int)
df.internet = (df.internet == 'yes').astype(int)

另请注意,您编写了将 yes' 和 no's 转换为 1s 和 0s,因此在您的代码示例中,您尝试以相反的方式分配值。


推荐阅读