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.
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.
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.
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.
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.
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.
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With