4

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!

1
  • you can try pd.concat([df,df1])
    – EdChum
    Oct 29, 2014 at 11:14

3 Answers 3

5

Please note that, as per here, Series are size-immutable (i.e. appending an entry to a Series will copy the original series and create a new object). This means that appending rows to a DataFrame will keep making unnecessary copies of the entire DataFrame. Highly recommend building a list with your rows, and then making one DataFrame when you have all the rows you need

0
4

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)
1

You can use .ix:

In [1]: df = pd.DataFrame(columns = ['COL1', 'COL2'])
In [2]: df.ix['test1'] = [20, 30]
In [3]: df
Out[3]:
       COL1  COL2
test1    20    30

[1 rows x 2 columns]
2
  • Thanks, but i get KeyError: 'test1', using python 2.7 Oct 29, 2014 at 16:04
  • @user2476373 it should work if pandas version >= 0.13.1. You can do pip freeze | grep -i pandas to check your pandas version and pip install -U pandas to update it.
    – Yang
    Oct 29, 2014 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.