首页 > 解决方案 > 将行的列表/值分配给列名

问题描述

该代码使用了一种热编码技术。

#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”分配给每个流派列,但是如何在这里将每行中的每种流派分配给单个列?

结果显示,每一行中的每个类型(喜剧、冒险、浪漫)都成为该数据框的新列。谢谢你。

这是上面代码之前的输出(之前) 在此处输入图像描述

这是上面代码之后的输出(之后)

在此处输入图像描述

标签: pythondataframeone-hot-encoding

解决方案


moviesWithGenres_df.at[index, genre] = 1

这一行将值分配给 row = index 和 column = 流派的数据框,哪个流派是保留流派字符串的变量(例如“喜剧”),因此如果数据框中不存在列,它将创建名称与参数列相同的新列(这是保留流派字符串的流派(例如“喜剧”)。

阅读本文档:https ://pandas.pydata.org/docs/reference/api/pandas.DataFrame.at.html


推荐阅读