1

I have a dataframe df that has a column tags . Each element of the column tags is a list of dictionary and looks like this:

[
    {
        "id": "leena123",
        "name": "LeenaShaw",
        "slug": null,
        "type": "UserTag",
        "endIndex": 0,
        "startIndex": 0
    },
    {
        "id": "1234",
        "name": "abc ltd.",
        "slug": "5678",
        "type": "StockTag",
        "endIndex": 0,
        "startIndex": 0
    }
]

The list can have any number of elements.

Sample dataset:

 0  some_data  [{'id': 'leena123', 'name': 'leenaShaw', 'slug': None, 'type...
 1  some data  [{'id': '6', 'name': 'new', 'slug': None, 'type...

I want to create a list of all the ids from the tags column where the type is UserTag

sample output: ['leena123', 'saily639,...]

I am trying with this : list(df['tags'].apply(lambda x: d['name'] if any(d['type'] == 'UserTag' for d in x)))

but it doesn't work. Kindly help pn this.

1
  • 1
    Please share a sample of your dataframe with expected output. Commented Apr 5, 2021 at 6:36

1 Answer 1

1

Use List Comprehension with df.apply:

df['id'] = df.tags.apply(lambda x: [i['id'] for i in x if i.get('type') == 'UserTag'])

Create a list from id column:

import itertools

l = df['id'].values.tolist()
output_id_list = list(itertools.chain(*l))

If you want to drop id column from df, do:

df.drop('id', inplace=True)
Sign up to request clarification or add additional context in comments.

4 Comments

This is creating a new column with the usertags. I want a list with the user tags as follows ['leena123', 'saily639,...]
You want to replace existing tags column?
No. I do not add the a new column or replace the existing tags. I want to have a list of the id where type is userTag.
@dipanjana Please check my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.