元素在Pandas DataFrame中的列表中的位置

时间:2018-11-25 14:24:35

标签: python pandas

新手在这里

我有一个Pandas DataFrame,其中包含如下列乘员列。看起来每一行都是一个列表。

    crewjob
    [Director, Screenplay, Screenplay, Screenplay,...
    [Executive Producer, Screenplay, Original Musi...
    [Director, Characters, Writer, Sound Recordist]
    [Director, Screenplay, Producer, Producer, Pro...
    [Original Music Composer, Director of Photogra...
    [Director, Screenplay, Producer, Producer, Ori...
    [Director, Screenplay, Producer, Original Musi...
    [Screenplay, Screenplay, Director, Novel]
    [Director, Screenplay, Screenplay, Producer, P...

我想为每一行提取导演在列表中的位置。 我尝试了枚举方法,但它排除了一个空白列表。

   indices = [i for i, x in enumerate(creditsdf['crewjob']) if x == "Director"]

我也尝试过.index方法

   creditsdf['test'] = creditsdf['crewjob'].index("Director")

哪个出现以下错误;

TypeError: 'RangeIndex' object is not callable

1 个答案:

答案 0 :(得分:0)

使用嵌套列表理解:

indices = [[i for i, x in enumerate(y) if x == "Director"] for y in increditsdf['crewjob']]
print (indices)
[[0], [], [0], [0], [], [0], [0], [2], [0]]