gesanghuayuan
gesanghuayuan

Reputation: 43

pandas extra a new header from a already exist header?

df = DataFrame({'DATE' : ['2017-01-01','2017-01-02'],'Sexuality/us' :['femle','male'],'Height/us' :[190,195]})

     DATE        Sexuality/us   Height/us  
0  2017-01-01        female         190   
1  2017-01-02        male           195   
  1. As you see this is a pandas DataFrame data
  2. I want to transfer this DataFrame to csv
  3. When I use df.to_csv('demo.csv') as blow

    the csv screenshot

  4. What I really want to get is like this(extract the us to another row, of course, there may be many countries, I want to extract countries to an row as header):

    final result I need

  5. Any one can help me? Thanks very much

Upvotes: 3

Views: 71

Answers (1)

Ted Petrou
Ted Petrou

Reputation: 61947

If you put DATE into the index then you can split your columns by / and create a multiindex.

df = df.set_index('DATE')
df.columns = df.columns.str.split('/', expand=True)
df.reset_index().swaplevel(axis=1)

                  us          
         DATE Height Sexuality
0  2017-01-01    190     femle
1  2017-01-02    195      male

Upvotes: 4

Related Questions