1

The objective is to append a string at the first row of a df.

The snippet below answer the objective

import pandas as pd
df = pd.DataFrame({'A': [11, 21, 31],
               'B': [12, 22, 32],
               'C': [13, 23, 33]},
              index=['ONE', 'TWO', 'THREE'])

df=df.astype ( str )
all_columns = list ( df )

df_new=pd.DataFrame(['test']*len(all_columns)).transpose()
df_new.columns=all_columns
df_new = df_new.astype ( str )
df33= pd.concat ( [df_new, df], axis=0 )

But I wonder whether there is more compact way that the proposed solution.

mpx
  • 3,081
  • 2
  • 26
  • 56

3 Answers3

3

append and concat are concise, but it's much more efficient to prepend the row as a list insertion:

data = df.to_numpy().tolist()
data.insert(0, ['test'] * len(df.columns))
pd.DataFrame(data, index=[0] + df.index.tolist(), columns=df.columns)

#           A     B     C
# 0      test  test  test
# ONE      11    12    13
# TWO      21    22    23
# THREE    31    32    33

Timings:

%%timeit
data = df.to_numpy().tolist()
data.insert(0, ['test'] * len(df.columns))
pd.DataFrame(data, index=[0] + df.index.tolist(), columns=df.columns)

# 413 µs ± 57 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
pd.DataFrame({c:['test'] for c in df.columns}).append(df)

# 807 µs ± 83.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
tdy
  • 36,675
  • 19
  • 86
  • 83
1

Here is a solution you can give it a try,

pd.DataFrame({c:['test'] for c in df.columns}).append(df)

          A     B     C
0      test  test  test
ONE      11    12    13
TWO      21    22    23
THREE    31    32    33
sushanth
  • 8,275
  • 3
  • 17
  • 28
1

Just a question, why not using MultiIndex to keep your column with the right dtype?

df.columns = pd.MultiIndex.from_product([df.columns, ['test']])
>>> df
         A    B    C
      test test test
ONE     11   12   13
TWO     21   22   23
THREE   31   32   33
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • This is a step before converting to another table form. But thanks for offering another perspective. – mpx Aug 05 '21 at 04:56