insert a list as row in a dataframe at a specific position

Viewed 2394

I have a list l=['a', 'b' ,'c']

and a dataframe with columns d,e,f and values are all numbers How can I insert list l in my dataframe just below the columns.

4 Answers

Setup

df = pd.DataFrame(np.ones((2, 3), dtype=int), columns=list('def'))
l = list('abc')

df

   d  e  f
0  1  1  1
1  1  1  1

Option 1
I'd accomplish this task by adding a level to the columns object

df.columns = pd.MultiIndex.from_tuples(list(zip(df.columns, l)))
df

   d  e  f
   a  b  c
0  1  1  1
1  1  1  1

Option 2
Use a dictionary comprehension passed to the dataframe constructor

pd.DataFrame({(i, j): df[i] for i, j in zip(df, l)})

   d  e  f
   a  b  c
0  1  1  1
1  1  1  1

But if you insist on putting it in the dataframe proper... (keep in mind, this turns the dataframe into dtype object and we lose significant computational efficiencies.)

Alternative 1

pd.DataFrame([l], columns=df.columns).append(df, ignore_index=True)

   d  e  f
0  a  b  c
1  1  1  1
2  1  1  1

Alternative 2

pd.DataFrame([l] + df.values.tolist(), columns=df.columns)

   d  e  f
0  a  b  c
1  1  1  1
2  1  1  1

Use pd.concat

In [1112]: df
Out[1112]:
          d         e         f
0  0.517243  0.731847  0.259034
1  0.318821  0.551298  0.773115
2  0.194192  0.707525  0.804102
3  0.945842  0.614033  0.757389

In [1113]: pd.concat([pd.DataFrame([l], columns=df.columns), df], ignore_index=True)
Out[1113]:
          d         e         f
0         a         b         c
1  0.517243  0.731847  0.259034
2  0.318821  0.551298  0.773115
3  0.194192  0.707525  0.804102
4  0.945842  0.614033  0.757389

Are you looking for append i.e

df = pd.DataFrame([[1,2,3]],columns=list('def'))
I = ['a','b','c']
ndf = df.append(pd.Series(I,index=df.columns.tolist()),ignore_index=True)

Output:

   d  e  f
0  1  2  3
1  a  b  c

If you want add list to columns for MultiIndex:

df.columns = [df.columns, l]
print (df)
   d  e  f
   a  b  c
0  4  7  1
1  5  8  3
2  4  9  5
3  5  4  7
4  5  2  1
5  4  3  0

print (df.columns)
MultiIndex(levels=[['d', 'e', 'f'], ['a', 'b', 'c']],
           labels=[[0, 1, 2], [0, 1, 2]])

If you want add list to specific position pos:

pos = 0
df1 = pd.DataFrame([l], columns=df.columns)
print (df1)
   d  e  f
0  a  b  c

df = pd.concat([df.iloc[:pos], df1, df.iloc[pos:]], ignore_index=True)
print (df)
   d  e  f
0  a  b  c
1  4  7  1
2  5  8  3
3  4  9  5
4  5  4  7
5  5  2  1
6  4  3  0

But if append this list to numeric dataframe, get mixed types - numeric with strings, so some pandas functions should failed.

Setup:

df = pd.DataFrame({'d':[4,5,4,5,5,4],
                   'e':[7,8,9,4,2,3],
                   'f':[1,3,5,7,1,0]})

print (df)
Related