python - 将行的列表/值分配给列名
问题描述
该代码使用了一种热编码技术。
#For every row in the dataframe, iterate through the list of genres and place a 1 into the corresponding column
for index, row in movies_df.iterrows():
for genre in row['genres']:
moviesWithGenres_df.at[index, genre] = 1
#Filling in the NaN values with 0 to show that a movie doesn't have that column's genre
moviesWithGenres_df = moviesWithGenres_df.fillna(0)
moviesWithGenres_df.head()
我想到了遍历数据帧的每个低点,并且我知道将“1”分配给每个流派列,但是如何在这里将每行中的每种流派分配给单个列?
结果显示,每一行中的每个类型(喜剧、冒险、浪漫)都成为该数据框的新列。谢谢你。
这是上面代码之后的输出(之后)
解决方案
moviesWithGenres_df.at[index, genre] = 1
这一行将值分配给 row = index 和 column = 流派的数据框,哪个流派是保留流派字符串的变量(例如“喜剧”),因此如果数据框中不存在列,它将创建名称与参数列相同的新列(这是保留流派字符串的流派(例如“喜剧”)。
阅读本文档:https ://pandas.pydata.org/docs/reference/api/pandas.DataFrame.at.html
推荐阅读
- symfony - Symfony 安全防火墙 JSON 响应
- reactjs - 在 Redux 表单中反应日期选择器
- r - 是否有一个功能可以平滑数据,同时将值分配到新的数据框中?
- javascript - 在循环中从数组中返回单词
- python - 如何使用 Python 在 Apache Ignite 中进行连续查询?
- mysql - 为什么我需要一个用于 wordpress 的 volumeclaim.yaml 而不是用于 mysql 数据库的 volumeclaim.yaml?
- android - 如何修复“java.lang.NumberFormatException:无效浮点数:“16.0dip””
- node.js - 用于收集的环回远程方法中的自定义 CRUD,而不是用于 mongodb 的模型
- go - 将int数组转换为字节数组,压缩然后反转
- django - django:本地主机突然停止工作?