1

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.

Mark P.
  • 1,827
  • 16
  • 37

1 Answers1

1

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          |
+---------------+
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
  • That works... thanks! Would you mind explaining what exactly its doing? I am not very familiar with lambda expressions... May help others too. Thanks! – Mark P. Dec 09 '19 at 02:58
  • 2
    It's converting from ['Butter', 'Salt', ...] to [['Butter'], ['Salt'], ...] tabulate needs to have a list of lists, or it splits the words – oppressionslayer Dec 09 '19 at 03:00