1

I have a dataframe which consists of a column having tags as

tags
------------
['tag1' 'tag2']
['tag1']
['tag5' 'tag3' 'tag6']

How to get the dataframe in following format?

    tags
    ------------
    ['tag1','tag2']
    ['tag1']
    ['tag5','tag3','tag6']

While viewing the single row:

print(df['tags'][0][0])
>>> "'tag1' 'tag2'"
print(df['tags'][0][0][0]
>>> "'"

I tried the following method:

def Convert(string): 
    li = list(string.split(" ")) 
    return li 
str1 = Convert(df1['tags'][0][0])
print(str1)
>>> ["'tag1'", "'tag2'"]

Method2 This also didn't work to me.

import ast
ast.literal_eval(df['tags'][0][0])
>>>'tag1tag2' 

Question2 I want to count the total occurrence of tags and df['tags'].value_counts() doesn't work. It either takes the whole list as count their occurrence or if i modify the list then it will take the character count.

3
  • Your objective is not clear to me. Do you want to split strings of the form " \'tag1\' \'tag2\' "? Commented Feb 28, 2021 at 8:09
  • 1
    Does this answer your question? pandas - convert string into list of strings Commented Feb 28, 2021 at 8:12
  • @JanAlexander I have a list say list1 = ['tag1' 'tag2'] and i want to access the list item tag1 and tag2. But the list is actually in form list1 = ["'tag1' 'tag2"'] . By accessing the list item, i mean in the format list1 = ['tag1','tag2'] Commented Feb 28, 2021 at 8:36

1 Answer 1

2

Is this what you are looking for?

list1 = ["'tag1' 'tag2'"]
result = [w.strip("'") for w in list1[0].split(' ')]
print(f'converted\n{list1}\nto\n{result}')
Sign up to request clarification or add additional context in comments.

Comments

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.