Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add new record to pandas dataframe

Tags:

python

pandas

I would like to add new records with new indices to a pandas dataframe for example:

df = pandas.DataFrame(columns = ['COL1', 'COL2'])

Now I have a new record, with index label 'Test1', and values [20, 30] i would like to do something like (pseudo code):

df.append(index='Test1', [20, 30])

so my result would be

       COL1   COL2
Test1   20     30

The furthest i've reached was:

df = df.append({'COL1':20, 'COL2':30}, ignore_index=True)

but this solution does not includes the new index

Thanks!

like image 935
Yuval Atzmon Avatar asked Oct 19 '25 14:10

Yuval Atzmon


1 Answers

Citing from the documentation here:

Warning Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

So, you should use loc instead

>>> import pandas as pd
>>> df = pd.DataFrame(columns = ['COL1', 'COL2'])
>>> df.loc['test1'] = [20, 30]
>>> df 
      COL1 COL2
test1   20   30
>>> df.shape 
(1, 2)
like image 80
Mohamed Ali JAMAOUI Avatar answered Oct 21 '25 02:10

Mohamed Ali JAMAOUI