-1

Looking to amend a df:

Test_Data = [
                ('Client', ['A','B','C']),
                ('2018-11', [10,20,30]),
                ('2018-12', [10, 20, 30]),
             ]

df = pd.DataFrame(dict(Test_Data))
print(df)

  Client  2018-11  2018-12
0      A       10       10
1      B       20       20
2      C       30       30

Desired output:

Report_Mongo    Client  Month_1  Month_2
0               Client  2018-11  2018-12
1               A       10       10
2               B       20       20
3               C       30       30

So move existing headers down one row and insert the new headers:

c = ['Report_Mongo','client', 'Month_1', 'Month_2']
Peter Lucas
  • 1,979
  • 1
  • 16
  • 27

1 Answers1

4

I suggest create MultiIndex for not mixing numeric with strings data in DataFrame:

c = ['Report_Mongo','client', 'Month_1', 'Month_2']

#get columns by list without first element
df.columns = [c[1:], df.columns]
#get first element to names of columns
df.columns.names = (c[0], '')
print(df)

Report_Mongo client Month_1 Month_2
             Client 2018-11 2018-12
0                 A      10      10
1                 B      20      20
2                 C      30      30

If need first row by columns it is possible with append, but most preferable is first solution:

c = ['Report_Mongo','client', 'Month_1', 'Month_2']

df = df.columns.to_frame().T.append(df, ignore_index=True)
df.columns = c[1:]
df.columns.name = c[0]
print(df)

Report_Mongo  client  Month_1  Month_2
0             Client  2018-11  2018-12
1                  A       10       10
2                  B       20       20
3                  C       30       30
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252