0

I have a dataframe that looks like this:

  Index Z1  Z2  Z3 Z4
    0   0   0   A  A
    1   0   B   0  0
    2   C   0   C  0

I want to convert it to

 Index  Z1  Z2  Z3 Z4
   ABC 
    0   0   0   A  A
    1   0   B   0  0
    2   C   0   C  0

I want to basically insert text "ABC" before 0th index and the entire row(ABC) will not have any value It will be okay if the index starts from 1 and not 0 as below

 Index  Z1  Z2  Z3 Z4
   ABC 
    1   0   0   A  A
    2   0   B   0  0
    3   C   0   C  0
Rookie_123
  • 1,975
  • 3
  • 15
  • 33

2 Answers2

3

It seems you need set index name or columns name. But there is possible some pandas function should remove it.

print (df.index.name)
None
print (df.columns.name)
Index

df.index += 1
df.index.name = 'ABC'
print (df)
Index Z1 Z2 Z3 Z4
ABC              
1      0  0  A  A
2      0  B  0  0
3      C  0  C  0

Better is create MultiIndex and select by loc:

mux = pd.MultiIndex.from_product([['ABC'], df.index + 1])
df = df.set_index(mux)
print (df)
      Z1 Z2 Z3 Z4
ABC 1  0  0  A  A
    2  0  B  0  0
    3  C  0  C  0

print (df.loc['ABC'])
  Z1 Z2 Z3 Z4
1  0  0  A  A
2  0  B  0  0
3  C  0  C  0

Also if need distingush many DataFrames with same structure use concat with parameter keys for MultiIndex:

#sample only, in real df1, df2, ... dfn
dfs = [df,df,df]
df = pd.concat(dfs, keys=('a','b','c'))
print (df)
    Z1 Z2 Z3 Z4
a 0  0  0  A  A
  1  0  B  0  0
  2  C  0  C  0
b 0  0  0  A  A
  1  0  B  0  0
  2  C  0  C  0
c 0  0  0  A  A
  1  0  B  0  0
  2  C  0  C  0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2
In [53]: df.rename_axis('ABC').rename_axis('Index',1)
Out[53]:
Index Z1 Z2 Z3 Z4
ABC
0      0  0  A  A
1      0  B  0  0
2      C  0  C  0

index starting with 1:

In [54]: df.set_index(df.index+1).rename_axis('ABC').rename_axis('Index',1)
Out[54]:
Index Z1 Z2 Z3 Z4
ABC
1      0  0  A  A
2      0  B  0  0
3      C  0  C  0

UPDATE:

Main purpose is that I have many such dataframe which I am appending to create a final csv.So inorder to differentiate between these dataframes in that final csv I am inserting text at the beginning of each dataframe

I would suggest to store your data in HDF5 file(s) - it has quite a few advantages compared to CSV:

Demo:

df.to_hdf(r'/path/to/file.h5', 'ABC', data_columns=True)
df2.to_hdf(r'/path/to/file.h5', 'DEF', data_columns=True)
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419