0

how to print lists horizontally in a table in python3? for eg

lists:

a=[1,2,4,6]
b=[2,4,5,6]
c=[4,5,86,6]
d=[3,4,6]

what I want is horizontally add these lists as 'a' as column and 'b' as another colomn and all the rest of the lists as separate columns.

how to achieve this in python, I tried texttable, tabulate, but no luck they won't allow to create table horizontally

chiju
  • 27
  • 2
  • 6
  • 2
    Hi Chiju, can you post some code examples of what you've tried so far? – Francis Sep 02 '18 at 22:26
  • Have you tried Pandas? And pivoting the dataframe? – OneCricketeer Sep 02 '18 at 23:30
  • Possible duplicate of [Getting list of lists into pandas DataFrame](https://stackoverflow.com/questions/19112398/getting-list-of-lists-into-pandas-dataframe) – Schalton Sep 02 '18 at 23:45
  • Hi Francis cricket_007, I tried textable,tabulate modules and panda itself but I missed out the .transpose() option, it is the meathod that I was looking for. – chiju Sep 03 '18 at 19:25

1 Answers1

1

You can use pandas to do this pretty simply. Pandas is also a great library for working with dataframes/tables in general.

Here's how you can read your data in as columns:

import pandas as pd

a=[1,2,4,6]
b=[2,4,5,6]
c=[4,5,86,6]
d=[3,4,6]

df = pd.DataFrame([a,b,c,d]).transpose()
df.columns = ['a', 'b', 'c', 'd']

Then df is equal to:

     a    b     c    d
0  1.0  2.0   4.0  3.0
1  2.0  4.0   5.0  4.0
2  4.0  5.0  86.0  6.0
3  6.0  6.0   6.0  NaN

I'm not sure what you mean by "all the lists as separate column" but I wouldn't recommend putting lists in cells in a DataFrame.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
  • .transpose() did the trick, Thanks for the help one more small issue is that all datas are print in left allinged, Is there a way to print them center(allingment as center) – chiju Sep 03 '18 at 19:19
  • @chijumelveettil that would need to be handled by modifying your lists before you put them in the DataFrame. You could get the max length of all the lists you have and then fill the rest with the appropriate number of `None`s at either end of the list. – Henry Woody Sep 03 '18 at 19:27