Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a value to the end of a pandas index object

Tags:

python

pandas

I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example

import pandas as pd
ser = pd.Series([1,2,3,4,5], index=[11,12,13,14,15])
indx = ser.index

Say I want to add the value 20 to the end of the index. This throws an error:

indx.append(20)

This returns [11,12,13,14,20,15]:

indx.insert(-1, 20)

This works but seems like a work-around:

indx.insert(len(indx), 20)

Is there something I'm missing? This is on pandas 0.18.1. Thanks.

like image 642
Alex Avatar asked Aug 30 '16 14:08

Alex


People also ask

How do you add data to an index in Python?

set_index() is used to set a new index to the DataFrame. It is also used to extend the existing DataFrame, i.e., we can update the index by append to the existing index. We need to use the append parameter of the DataFrame. set_index() function to append the new index to the existing one.

How do you append an index?

Example #1: Use Index. append() function to append a single index to the given index. Output : Let's append df2 index at the end of df1.

How do I get the last element in Pandas?

Python3. Pandas iloc is used to retrieve data by specifying its integer index. In python negative index starts from end therefore we can access the last element by specifying index to -1 instead of length-1 which will yield the same result.

What does .index do in Pandas?

Index is like an address, that's how any data point across the dataframe or series can be accessed. Rows and columns both have indexes, rows indices are called as index and for columns its general column names.


3 Answers

The method append takes another index as input, but union will work if you simply pass an array-like object:

indx.union([20])

Note that index objects in pandas are immutable, so any such operation will return a new index rather than modifying the existing one.

like image 101
IanS Avatar answered Oct 12 '22 23:10

IanS


You need to pass a collection of index values as parameter while appending to the given index object.

indx.append(pd.Index([20]))   # Pass the values inside the list 
Int64Index([11, 12, 13, 14, 15, 20], dtype='int64')
like image 30
Nickil Maveli Avatar answered Oct 13 '22 00:10

Nickil Maveli


You may want to try these two options:

import pandas as pd
import numpy as np
ser.append(pd.Series([np.nan], index = [20]))

# 11    1.0
# 12    2.0
# 13    3.0
# 14    4.0
# 15    5.0
# 20    NaN
# dtype: float64

ser.set_value(20, np.nan)

# 11    1.0
# 12    2.0
# 13    3.0
# 14    4.0
# 15    5.0
# 20    NaN
# dtype: float64
like image 39
Psidom Avatar answered Oct 12 '22 23:10

Psidom