pythonpandas

Pasting data into a pandas dataframe


This is the same question as this question, which is marked as a duplicate of this one.
The problem, and the reason I'm still asking, is that the solution provided (using pandas.read_clipboard()) currently doesn't work.
I use Python 3.5 and whenever I try to copy data from the clipboard I get an error :

"It seems the kernel died unexpectedly" which seems to be restricted to 3.5.

Any other way to get a simple dataframe like the one below in a pandas dataframe without resorting to manually typing it or downgrading Python?

   c1  c2  c3  c4
0   1   2   2   1
1   1   3   2   3
2   3   4   4   3
3   4   5   6   5
4   5   6   9   7

in R I would be usingread.table() with the text= argument

Thank you for your help.


Solution

  • You can use io.StringIO with pd.read_table:

    import io
    s = '''
       c1  c2  c3  c4
    0   1   2   2   1
    1   1   3   2   3
    2   3   4   4   3
    3   4   5   6   5
    4   5   6   9   7
    '''
    
    pd.read_table(io.StringIO(s), delim_whitespace=True)
    Out: 
       c1  c2  c3  c4
    0   1   2   2   1
    1   1   3   2   3
    2   3   4   4   3
    3   4   5   6   5
    4   5   6   9   7