How do you read in a dataframe with lists using pd.read_clipboard?

前端 未结 5 812
无人及你
无人及你 2021-01-05 00:33

Here\'s some data from another question:

                          positive                 negative          neutral
1   [marvel, moral, bold, destiny]              


        
5条回答
  •  情书的邮戳
    2021-01-05 00:54

    Per help from @MaxU

    df = pd.read_clipboard(sep='\s{2,}', engine='python')
    

    Then:

    >>> df.apply(lambda col: col.str[1:-1].str.split(', '))
                             positive                negative         neutral
    1  [marvel, moral, bold, destiny]                      []  [view, should]
    2                     [beautiful]     [complicated, need]              []
    3                     [celebrate]  [crippling, addiction]           [big]
    
    >>> df.apply(lambda col: col.str[1:-1].str.split()).loc[3, 'negative']
    ['crippling', 'addiction']
    

    And per the notes from @unutbu who came up with a similar solution:

    assumes the first and last character in each cell is [ and ]. It also assumes there is exactly one space after the commas.

提交回复
热议问题