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

前端 未结 5 810
无人及你
无人及你 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:50

    TL;DR

    For basic structures you can use yaml without having to add quotes:

    import yaml
    df = pd.read_clipboard(sep='\s{2,}').applymap(yaml.load)
    
    type(df.iloc[0, 0])
    Out: list
    

    Full Answer

    Under certain conditions, you can read your lists as strings and the convert them using literal_eval (or pd.eval, if they are simple lists).

    For example,

               A   B
    0  [1, 2, 3]  11
    1  [4, 5, 6]  12
    

    First, ensure there are at least two spaces between the columns, then copy your data and run the following:

    import ast 
    
    df = pd.read_clipboard(sep=r'\s{2,}', engine='python')
    df['A'] = df['A'].map(ast.literal_eval)    
    df
        
               A   B
    0  [1, 2, 3]  11
    1  [4, 5, 6]  12
    
    df.dtypes
    
    A    object
    B     int64
    dtype: object
    

    Notes

    • for multiple columns, use applymap in the conversion step:

      df[['A', 'B', ...]] = df[['A', 'B', ...]].applymap(ast.literal_eval)
      
    • if your columns can contain NaNs, define a function that can handle them appropriately:

      parser = lambda x: x if pd.isna(x) else ast.literal_eval(x)
      df[['A', 'B', ...]] = df[['A', 'B', ...]].applymap(parser)
      
    • if your columns contain lists of strings, you will need something like yaml.load (requires installation) to parse them instead if you don't want to manually add quotes to the data. See above.

提交回复
热议问题