0

I want an organized output

for ind in df.index: 
     print(df['Name'][ind], df['Stream'][ind].rjust(15," ")) 

I did this but I'm not getting the expected output

import pandas as pd 
data = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'], 
                'Age': [21, 19, 20, 18], 
                'Stream': ['Math', 'Commerce', 'Arts', 'Biology'], 
                'Percentage': [88, 92, 95, 70]} 
df = pd.DataFrame(data, columns = ['Name', 'Age', 'Stream', 'Percentage']) 
print("Given Dataframe :\n", df) 
print("\nIterating over rows using index attribute :\n")  
for ind in df.index: 
     print(df['Name'][ind], df['Stream'][ind]) 

Output:

Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology

Expected output:

Ankit         Math
Amit          Commerce
Aishwarya     Arts
Priyanka      Biology

I want my output like expected output i have tried with right alignment but not getting the expected output; how can I get this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

1

You can specify the width of each item you want to print. Below, I specify a width of 10 characters for printing the Name.

for ind in df.index: 
     print("{:10} {}".format(df['Name'][ind], df['Stream'][ind]) )
0

Have you considered printing it as table ? you need to import following:

from tabulate import tabulate

OR:

for i in range(10): print '%-12i%-12i' % (10 ** i, 20 ** i)

Also see: Printing Lists as Tabular Data

Andi
  • 63
  • 9