将行的列表/值分配给列名

2024-10-02 16:28:50 发布

您现在位置: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”分配给每一个类型列,但是如何将每一行中的每一个类型分配给一个列呢

结果显示,每一行中的每一个genre(喜剧、进步、浪漫)都成为此数据帧的一个新列。多谢各位

这是上述代码之前的输出(之前) enter image description here

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

enter image description here


Tags: the数据代码in类型编码dffor
1条回答
网友
1楼 · 发布于 2024-10-02 16:28:50
moviesWithGenres_df.at[index, genre] = 1

此行在row=index和column=genre处为数据帧赋值 哪种体裁是保持一串体裁的变量(如“喜剧”) 所以,若数据帧中不存在列,它将创建一个与参数列同名的新列(这是保留类型字符串的类型(如“喜剧”)

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

相关问题 更多 >