python - 使用 pandas 从一列字典创建一个热编码

标签 python pandas dataframe

我正在开发一个使用公共(public) IMDB 数据集的项目,并希望从每个子字符串中提取流派数据并将此信息存储在单独的列中。这就是我目前所拥有的。

当前: ID流派 1995 [{"id": 28, "name": " Action "}, {"id": 12, "name": "冒险"}, {"id": 14, "name": "幻想"}, {"id": 878, "name": "科幻小说"}]

我想要实现的目标 是将数据分成每个类型,对应于电影ID,例如电影ID 1995 年: Action 、冒险、奇幻、科幻

总而言之,我有多个包含我想要的字符串,我想为每个 ID 提取相关数据(流派)。

我怎样才能在Python中做到这一点,我一直在玩pandas,但目前只能获得一种类型的真/假。

CSV 文件 here

import pandas as pd
import numpy as np
import os
import re
import matplotlib.pyplot as plt
# Order of the Column headers for the re-arranged data

Genres = ['Action','Adventure','Biography','Comedy','Crime','Documentary','Drama','Family','Fantasy',
          'Film-Noir''History','Horror','Musical','Mystery','News','Romance','Sci-Fi','Short','Sport',
          'Thriller','War','Western']

os.chdir('C:\\Users\parmi\Documents\Python Scripts')
org_data = pd.read_csv('tmdb_5000_movies.csv')


film_id = pd.DataFrame(org_data)['id']
genre_data = pd.DataFrame(org_data)['genres']

genre_data= genre_data.str.extract(Genre)
genre_combined = pd.concat([film_id,genre_data], axis=1)
genre_combined.to_csv('genre_data2.csv')

最佳答案

首先,加载您的数据 -

df = pd.read_csv('tmdb_5000_movies.csv')

接下来,genres 包含 JSON 数据,因此将其作为一列字典加载 -

v = df.genres.apply(json.loads)

接下来,使用 np.repeat 展平数据 -

df = pd.DataFrame(
{
    'id' : df['id'].values.repeat(v.str.len(), axis=0),
    'genre' : np.concatenate(v.tolist())
})

通过从每个字典中检索 name 属性,将 genre 从一列字典转换为一列字符串。

df['genre'] = df['genre'].map(lambda x: x.get('name'))

最后,使用 str.get_dummies 计算一个热门编码 -

ohe = df.set_index('id')\
        .genre.str.get_dummies()\
        .sum(level=0)\

ohe.head(10)

        Action  Adventure  Animation  Comedy  Crime  Documentary  Drama  \
id                                                                        
19995        1          1          0       0      0            0      0   
285          1          1          0       0      0            0      0   
206647       1          1          0       0      1            0      0   
49026        1          0          0       0      1            0      1   
49529        1          1          0       0      0            0      0   
559          1          1          0       0      0            0      0   
38757        0          0          1       0      0            0      0   
99861        1          1          0       0      0            0      0   
767          0          1          0       0      0            0      0   
209112       1          1          0       0      0            0      0   

        Family  Fantasy  Foreign  History  Horror  Music  Mystery  Romance  \
id                                                                           
19995        0        1        0        0       0      0        0        0   
285          0        1        0        0       0      0        0        0   
206647       0        0        0        0       0      0        0        0   
49026        0        0        0        0       0      0        0        0   
49529        0        0        0        0       0      0        0        0   
559          0        1        0        0       0      0        0        0   
38757        1        0        0        0       0      0        0        0   
99861        0        0        0        0       0      0        0        0   
767          1        1        0        0       0      0        0        0   
209112       0        1        0        0       0      0        0        0   

        Science Fiction  TV Movie  Thriller  War  Western  
id                                                         
19995                 1         0         0    0        0  
285                   0         0         0    0        0  
206647                0         0         0    0        0  
49026                 0         0         1    0        0  
49529                 1         0         0    0        0  
559                   0         0         0    0        0  
38757                 0         0         0    0        0  
99861                 1         0         0    0        0  
767                   0         0         0    0        0  
209112                0         0         0    0        0 

关于python - 使用 pandas 从一列字典创建一个热编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48213149/

相关文章:

Python,负值不超出列表范围

python - ubuntu 上 python 的应用程序引擎导入本地数据存储

python - 使用 Python 编写控制台输出(空格分隔的文本)以分隔 Excel 工作表的列

python - 使用 Python 从电子邮件中提取 URL

python - 在 Python 中向下舍入日期时间对象

python - 如何处理 pandas 数据帧中特定长度序列中的缺失值?

python - 如何突出显示数据帧的两个不同列中的唯一数据值?

dataframe - 达斯克-Kubernetes-教程示例

python - 提取与 Orange 的关联规则时出现问题?

python - 需要了解如何将数据分成同一图表上的两条单独的线