Search code examples
pythonpandastabulate

Python Tabulate formats characters as separate columns


Using pandas, I am reading in a tab delimited file that looks like this:

enter image description here

with the following code:

pantry_file = pd.read_csv('/PantryList.txt', sep='\t')

Based on user input, I want to print out a nice looking table of all Items in this file. I am using tabulate to do this. The code looks like this:

print(tabulate(pantry_file.loc[: , "ITEM"], tablefmt='psql', headers=['Pantry Item'], showindex=False))

However, the resulting output treats each character as a column:

enter image description here

Wheres a traditional print statement looks like this:

enter image description here

My question is, why is tabulate treating each letter as a column, and how can I correct this?

Other info: Python 3.6 using Spyder through Anaconda.


Solution

  • This should fix it:

    print(tabulate(list(map(lambda x:[x], pantry_file.loc[:, "ITEM"])), tablefmt='psql', headers=['Pantry Item'], showindex=False))
    

    output:

    +---------------+
    | Pantry Item   |
    |---------------|
    | Butter        |
    | Salt          |
    | Chicken       |
    | Beef Broth    |
    | Pepper        |
    | Milk          |
    +---------------+