Noob Coder
Noob Coder

Reputation: 233

How to find index of a list in a new dataframe by mapping?

I have a dataframe which contains list,

df = pd.DataFrame({'Item': [['hi', 'hello', 'bye'], ['school', 'pen'], ['hate', 'love', 'feelings', 'sad']]})


print(df)

    Item
0   [hi, hello, bye]
1   [school, pen]
2   [hate, love, feelings, sad]

Expected output:

    mapped_value
0   [0, 1, 2]
1   [0, 1]
2   [0, 1, 2, 3]

I tried using map(). I also used

df['mapped value'] = [i for i, x in enumerate(df['Item'][0])]
df

which gives me the wrong output. I need the index for the whole list, but nothing works, can someone please guide?

Upvotes: 1

Views: 193

Answers (1)

jezrael
jezrael

Reputation: 862681

You can use nested list comprehension:

df['mapped value'] = [[i for i, x in enumerate(x)] for x in df['Item']]

Or lambda function:

df['mapped value'] = df['Item'].apply(lambda x: [i for i, x in enumerate(x)])

Upvotes: 2

Related Questions