Home > Software design >  Adding array to Pandas dataframe as row
Adding array to Pandas dataframe as row

Time:01-17

I want to add an array to an existing pandas dataframe as row. Below is my code :

import pandas as pd
import numpy as np

data = [['tom', 10]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
print(df)

Y = [10, 100]

df.loc[0] = list(Y)
print(df)

Basically I want to add Y to df as row without disturbing existing rows. I also want to add column names of final df as 'Y1' and 'Y2'

Clearly with above code existing information of df appears to be replaced with Y.

Could you please help me with right code?

CodePudding user response:

Use loc adding the value by exiting row and additional columns

df.loc[0,['Y1','Y2']] =Y
df
  Name  Age    Y1     Y2
0  tom   10  10.0  100.0
  •  Tags:  
  • Related