0

This is probably pretty basic question, but I am stuck here. I would like to print a empty pandas dataframe on console with headers. I will try to explain it here.

I create a dataframe with a dictionary and print it, it prints the data with headers.

>>> details = {'EmpId' : [1, 2],'EmpName' : ["A", "B"]}
>>> df = pd.DataFrame(details)
>>> print(df)
   EmpId EmpName
0      1       A
1      2       B

But if for some reason dataframe is empty, then it just prints Empty DataFrame.

>>> import pandas as pd
>>> df = pd.DataFrame(columns=['Emp Id', 'Emp Name'])
>>> print (df)
Empty DataFrame
Columns: [Emp Id, Emp Name]
Index: []

Question here is - is it possible to display something like below

>>> print(df)
    EmpId  EmpName

2 Answers 2

1
DF_01=pd.DataFrame(columns=['Emp Id', 'Emp Name'])
DF_02=details = pd.DataFrame({'EmpId' : [1, 2],'EmpName' : ["A", "B"]})
        
def PrintDF(Dataframe):
  if len(Dataframe.index)==0:
    Strs=''
    for i in Dataframe.columns:
      Strs+=str(i)+'  '
    print(Strs[:-1])
  else:
    print(Dataframe)

PrintDF(DF_01) output:

Emp Id  Emp Name

PrintDF(DF_02) output:

     EmpId EmpName
0      1       A
1      2       B
Sign up to request clarification or add additional context in comments.

Comments

0

Use to_markdown().

For empty dataframe:

df = pd.DataFrame(columns=['Emp Id', 'Emp Name'])
print(df.to_markdown())

Output:

| Emp Id   | Emp Name   |
|----------|------------|

For dataframe with data:

details = {'EmpId' : [1, 2],'EmpName' : ["A", "B"]}
df = pd.DataFrame(details)
print(df.to_markdown())

Output:

|    |   EmpId | EmpName   |
|---:|--------:|:----------|
|  0 |       1 | A         |
|  1 |       2 | B         |

Refer https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_markdown.html for more table formatting details.

2 Comments

Thanks Azhar. Markdown seems to return string. Is there any option to get it as data frame itself so that I can use it for further processing?
You've df as dataframe. What are you trying to achieve?

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.