python - 在 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
我正在尝试创建一个线性回归模型,并希望将“是”和“否”转换为romantic
和internet
列中的 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'
即使我认为我改变了他们。请帮忙,谢谢...
解决方案
要转换您感兴趣的两个列,请运行:
df.romantic = (df.romantic == 'yes').astype(int)
df.internet = (df.internet == 'yes').astype(int)
另请注意,您编写了将 yes' 和 no's 转换为 1s 和 0s,因此在您的代码示例中,您尝试以相反的方式分配值。
推荐阅读
- python - Pandas 系列在系列对象的开头添加索引和值
- android - Android Studio BroadcastReceiver 在 Android 6.0 中不工作
- python - django - 尽管声明了默认值,但此字段是必需的错误
- if-statement - Azure 数据工厂中的 IF 表达式
- c - 如何在 for 循环中使用 scanf 以使其在第一次尝试时不会停止循环?
- reactjs - 如果其他类型存在,如何使类型可选?
- printing - 需要使用斑马打印机从 zpl ii 命令打印希腊字符
- typescript - 打字稿:从通用对象中删除键
- linux - bash脚本循环而日期不同mydate
- swift - 如何检查文本是否转到 UILabel 中的新行?