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
CodePudding user response:
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)
Emp Id Emp Name
PrintDF(DF_02)
EmpId EmpName 0 1 A 1 2 B
CodePudding user response:
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.