28

I am trying to convert my output into a pandas data frame and I am struggling. I have this list

my_list = [1,2,3,4,5,6,7,8,9]

I want to create a pandas data frame that would have 3 columns and three rows. I try using

df = pd.DataFrame(my_list, columns = list("abc"))

but it doesn't seem to be working for me. Any help would be appreciated.

Kay
  • 1,745
  • 3
  • 14
  • 23
  • 5
    I'd like to take a poll. If you landed up on this page and the accepted answer was not helpful to you, please ping me and let me know what it is you were searching the answer to. – cs95 Apr 17 '19 at 10:18
  • yup, converting other types of lists to pandas dataframe. e.g., `list = [['a', 1], ['a', 2], ['b', 1]]` converted to a two-column/Series dataframe – Brian D Jun 26 '19 at 02:21

1 Answers1

60

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090
  • 3
    is there any way the dimensions supplied to reshape can be picked up automatically? Say all I have to do is to know how many columns I want and pandas will automatically find the rows that fit for me – Kay Mar 04 '17 at 08:10
  • Maybe need `df = pd.DataFrame(np.array(my_list).reshape(3,-1), columns = list("abc"))` – jezrael Mar 04 '17 at 08:40
  • 8
    using `.... .reshape(3,-1) ` didn't really work for me. I used `.... .reshape(-1,3) ` and it seemed to work. I actually felt the dimensions are rows by columns and that's why I did that – Kay Mar 06 '17 at 21:42