Copying excel data into a python list in IPython u

2019-03-25 06:34发布

问题:

Is there a way to perform the following workflow:

  1. Select cells in an Excel spreadsheet
  2. Copy them using Ctrl+C
  3. Get the content the selected cells in a form of a python list or numpy array into the IPython shell?

回答1:

Update: It seems that the readline thing that @PauloAlmeida mentioned is turned on by default in the 1.0 verison of IPython. So all you have to do is:

  1. from numpy import array
  2. Copy the cells from the spreadsheet
  3. Hit Alt+V instead of Ctrl+V

And you will get in IPython something like:

array([[1, 1], [2, 2]])

Or you can use the pandas library read_clipboard method.

import pandas as pd
pd.read_clipboard()            # If you have selected the headers
pd.read_clipboard(header=None) # If you haven't selected the headers

This will return you a pandas DataFrame object which acts similarly to a spreadsheet. You can find more about it in their official documentation.



回答2:

Here is what I usually do:

1: get a csv file

Copy-paste the cells you want into a new Excel document. Click 'File' then 'Save as'. Select 'Save as type: CSV' . Close Excel and open the file with notepad or other editor.

Now you have something like this:

1, 2, 3
4, 5, 6

2: get a python list

You can either

  • use csv to load your csv file; or
  • use the search/replace functionality of your editor to replace start/end of lines with '[' and ']' then copy paste to ipython.


回答3:

If you are on Windows, you can use PyReadline, which has a smart paste feature:

  • Copy and paste using the clipboard
  • Smart paste for convenient use with ipython. Converting tab separated data to python list or numpy array.

See also the documentation for clipboard functions:

ipython_paste

Paste windows clipboard. If enable_ipython_paste_list_of_lists is True then try to convert tabseparated data to repr of list of lists or repr of array. If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space.