2

I want to align Python dataframe output to center of console or output file. I have tried below code:

import pandas as pd
import os   
cols = ('Employee Name','Employee AGE')
df = pd.read_csv("C:/Pawni/Desktop/test.csv",names = cols)
print(df.center(os.get_terminal_size().columns))

But it is giving error : AttributeError: 'DataFrame' object has no attribute 'center'

So, it seems Center is not a attribute of dataframe. What other options available to print dataframe output to center of console.

2 Answers 2

1

You could try to use shutil module, and split method

import shutil
import pandas as pd

data = {'test': [1,2,3], 'data': [4,5,6]}
df = pd.DataFrame(data)

# convert DataFrame to string
df_string = df.to_string()
df_split = df_string.split('\n')

columns = shutil.get_terminal_size().columns
for i in range(len(df)):
    print(df_split[i].center(columns))      
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure if this works entirely, but you might can use the to_string() method on the dataframe. .center() only works on a string.

import pandas as pd
data = {'test': [1,2,3], 'data': [4,5,6]}
df = pd.DataFrame(data)

# convert the DataFrame to a string
df_string = df.to_string()

# print the centered string
print(df_string.center(os.get_terminal_size().columns))

1 Comment

I have tried this but getting error: OSError: [WinError 6] The handle is invalid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.