清洗数据框列

时间:2020-04-22 15:16:03

标签: python pandas dataframe

我正在尝试从数据框中的一列中删除所有不相关的信息,但不知道如何执行。我将数据从CSV文件直接导入到数据框。

所以目前我的类型栏如下:

{'genres': {0: [{"id": 28, "name": "Action"}, {"id": 12, "name": 'Fantasy'}, etc.

我希望它看起来像这样:

{'genres': {0: "['Action', 'Fantasy']"}, etc.

如果有人可以帮助我或以正确的方向将其发送给我,将不胜感激。

1 个答案:

答案 0 :(得分:0)

根据描述中的唯一索引,可能是您要寻找的,explodetransform到系列,groupby使用索引,list所有名称: / p>

data = {'genres':
        {0: [{"id": 28, "name": "Action"}, {"id": 12, "name": 'Fantasy'}],
         1: [{"id": 40, "name": "Crime"}, {"id": 24, "name": 'Thriller'}]
         }}

df = pd.DataFrame(data)
df.head()

#       genres
# 0 [{'id': 28, 'name': 'Action'}, {'id': 12, 'nam...
# 1 [{'id': 40, 'name': 'Crime'}, {'id': 24, 'name...

执行上述步骤:

df['genres_fix'] = df.genres.explode().transform(
    pd.Series).groupby(level=0)['name'].apply(list)

df[['genres_fix']].head()

#   genres_fix
# 0 [Action, Fantasy]
# 1 [Crime, Thriller]
相关问题