Skip to content
Advertisement

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

Here’s some data from another question:

JavaScript

What I would do first is to add quotes across all words, and then:

JavaScript

Is there a smarter way to do this?

Advertisement

Answer

Lists of strings

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

JavaScript

Lists of numeric data

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,

JavaScript

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

JavaScript

Notes

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

    JavaScript
  • if your columns can contain NaNs, define a function that can handle them appropriately:

    JavaScript
  • 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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement