Reputation: 25
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.
Upvotes: 2
Views: 1950
Reputation: 1441
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))
Upvotes: 1
Reputation: 1396
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))
Upvotes: 0