user1401472
user1401472

Reputation: 2301

Pandas Print Empty Data Frame with headers

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

Upvotes: 0

Views: 552

Answers (2)

Davey Kwok
Davey Kwok

Reputation: 11

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

Upvotes: 1

Azhar Khan
Azhar Khan

Reputation: 4098

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.

Upvotes: 0

Related Questions