pandas - convert string into list of strings

前端 未结 6 1821
故里飘歌
故里飘歌 2020-12-15 22:50

I have this \'file.csv\' file to read with pandas:

Title|Tags
T1|\"[Tag1,Tag2]\"
T1|\"[Tag1,Tag2,Tag3]\"
T2|\"[Tag3,Tag1]\"

using



        
6条回答
  •  一个人的身影
    2020-12-15 23:17

    Your df['Tags'] appears to be a list of strings. If you print that list you should get ["[tag1,tag2]","[Tag1,Tag2,Tag3]","[Tag3,Tag1]"] this is why when you call the first element of the first element you're actually getting the first single character of the string, rather than what you want.

    You either need to parse that string afterward. Performing something like

    df['Tags'][0] = df['Tags'][0].split(',')
    

    But as you saw in your cited example this will give you a list that looks like

    in: df['Tags'][0][0] 
    out: '[tag1'`
    

    What you need is a way to parse the string editing out multiple characters. You can use a simple regex expression to do this. Something like:

     import re
     df['Tags'][0] = re.findall(r"[\w']+", df['Tags'][0])
     print(df['Tags'][0][0])
    

    will print:

     'tag1'
    

    Using the other answer involving Pandas converters you might write a converter like this:

     def clean(seq_string):
          return re.findall(r"[\w']+", seq_string)
    

    If you don't know regex, they can be quite powerful, but also unpredictable if you're not sure on the content of your input strings. The expression used here r"[\w']+" will match any common word character alpha-numeric and underscores and treat everything else as a point for re.findall to split the list at.

提交回复
热议问题