Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a row to a MultiIndex DataFrame/Series

Tags:

I was wondering if there is an equivalent way to add a row to a Series or DataFrame with a MultiIndex as there is with a single index, i.e. using .ix or .loc?

I thought the natural way would be something like

row_to_add = pd.MultiIndex.from_tuples() df.ix[row_to_add] = my_row 

but that raises a KeyError. I know I can use .append(), but I would find it much neater to use .ix[] or .loc[].

here an example:

>>> df = pd.DataFrame({'Time': [dt.datetime(2013,2,3,9,0,1), dt.datetime(2013,2,3,9,0,1)], 'hsec': [1,25], 'vals': [45,46]}) >>> df                  Time  hsec  vals 0 2013-02-03 09:00:01     1    45 1 2013-02-03 09:00:01    25    46  [2 rows x 3 columns] >>> df.set_index(['Time','hsec'],inplace=True) >>> ind = pd.MultiIndex.from_tuples([(dt.datetime(2013,2,3,9,0,2),0)],names=['Time','hsec']) >>> df.ix[ind] = 5  Traceback (most recent call last):   File "<pyshell#201>", line 1, in <module>     df.ix[ind] = 5   File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 96, in __setitem__     indexer = self._convert_to_indexer(key, is_setter=True)   File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 967, in _convert_to_indexer     raise KeyError('%s not in index' % objarr[mask]) KeyError: "[(Timestamp('2013-02-03 09:00:02', tz=None), 0L)] not in index" 
like image 899
user3820991 Avatar asked Jul 23 '14 18:07

user3820991


People also ask

How do I add a row to an existing data frame?

You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement. Other options available to add rows to the dataframe are, append()

How do you add a row to a series in Python?

To append or add a row to DataFrame, create the new row as Series and use DataFrame. append() method.

How do I manually add a row to a DataFrame?

Add a Row to a Pandas DataFrame The easiest way to add or insert a new row into a Pandas DataFrame is to use the Pandas . append() method. The . append() method is a helper method, for the Pandas concat() function.


1 Answers

You have to specify a tuple for the multi-indexing to work (AND you have to fully specify all axes, e.g. the : is necessary)

In [26]: df.ix[(dt.datetime(2013,2,3,9,0,2),0),:] = 5  In [27]: df Out[27]:                            vals Time                hsec       2013-02-03 09:00:01 1       45                     25      46 2013-02-03 09:00:02 0        5 

Easier to reindex and/or concat/append a new dataframe though. Generally setting (with this kind of enlargement), only makes sense if you are doing it with a small number of values. As this makes a copy when you do this.

like image 99
Jeff Avatar answered Sep 24 '22 15:09

Jeff