Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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.

like image 861
Humi Avatar asked Dec 20 '25 03:12

Humi


2 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
like image 104
piRSquared Avatar answered Dec 22 '25 19:12

piRSquared


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
like image 28
Zero Avatar answered Dec 22 '25 18:12

Zero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!