CarlosLplz
CarlosLplz

Reputation: 11

How to create a Csv file from multiple dataframes in pandas with the name of the dataframe as a header of each column?

Suppose I have a dataframe A, a dataframe B, a dataframe C,with the following data:

Dataframe A:

Name   |  ID | Birthda  | Age   | Hobbies| WebPage |  
 ------|-----|----------|-------|--------|---------|-- 
  ...  | ... | ...      | ...   | ...    | ...     |  
  ...  | ... | ...      | ..... | ....   | ....    |  
  ...  | ..  | ...      | ...   | ...    | .....   |  

Dataframe B

 Name  | Experience | Places | Foods | Languages 
 ------|------------|--------|-------|----------- 
  ...  | .......    | ...... | ..... | .......   
  ...  | .....      | .....  | ..... | ......    
  ...  | ...        | ....   | ....  | .....     
       |            |        |       |           

Dataframe C

Actor   | Movies | Places | Date | Animals | Music 
 -------|--------|--------|------|---------|------- 
  ...   | ....   | ....   | ...  | ....    | ....  
  ....  | ....   | ....   | .... | ....    | ....

So, I'm only interested in the headers( columns names), I need to crate a csv that contains the dataframe's names as the csv file header and the headers as elements of each csv columns. The csv file must be Like this:

DataframeA   | DataframeB | DataframeC  |  
 ------------|------------|------------|-- 
  Name       | Experience | Actor      |  
  ID         | Name       | Movies     |  
  Birthday   | Places     | Places     |  
  Age        | Foods      | Date       |  
  Hobbies    | Languages  | Animals    |  
  WebPage    |            | Music      |

Upvotes: 0

Views: 55

Answers (1)

rafaelc
rafaelc

Reputation: 59274

Simply

pd.DataFrame({'DataFrame A': dfa.columns, 
              'DataFrame B': dfb.columns, 
              'DataFrame C': dfc.columns}).to_csv('file.csv')

if you have same length.

For different lengths,

pd.DataFrame([dfa.columns, 
              dfb.columns, 
              dfc.columns], index=['DataFrame A', 'DataFrame B', 'DataFrame C']).T.fillna('').to_csv('file.csv')

Upvotes: 1

Related Questions