Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list into table - python

Tags:

python

I have two arrays. column_names hold the column titles. values hold all the values.

I understand if I do this:

column_names = ["a", "b", "c"]
values = [1, 2, 3]
for n, v in zip(column_names, values):
    print("{} = {}".format(n, v))

I get

a = 1
b = 2
c = 3

How do I code it so if I pass:

column_names = ["a", "b", "c"]
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]

I would get

a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

Thank you!

like image 916
RJK Avatar asked Apr 26 '26 19:04

RJK


1 Answers

With pandas and numpy it is easy and the result will be a much more useful table. Pandas excels at arranging tabular data. So lets take advantage of it: install pandas with:

pip install pandas --user
#pandas comes with numpy
import numpy as np
import pandas as pd

# this makes a normal python list for integers 1-9
input = list(range(1,10))

#lets convert that to numpy array as np.array
num = np.array(input)

#currently its shape is single dimensional, lets change that to a two dimensional matrix that turns it into the clean breaks you want
reshaped = num.reshape(3,3)

#now construct a beautiful table
pd.DataFrame(reshaped, columns=['a','b','c'])

#ouput is
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
like image 145
csevier Avatar answered Apr 28 '26 10:04

csevier