This succinct article is about adding and inserting new elements to an existing Series in Pandas.
Before we begin, allow me to clarify an important point: “add elements” implies appending new elements to the end of the Series, while “insert elements” implies inserting new elements at a specific position in the Series.
Adding Elements to a Series
In the old days, the append() method was also a popular approach for this task, but is now depreciated so I won’t mention it anymore (it still works but you will see some annoying warnings when running your code).
Instead, for new Pandas projects, you should use the pd.concat() function to append a single value, a list of values, or another Series object to a given Series. This will return a new Series object with the combined elements.
Example:
import pandas as pd
s1 = pd.Series([10, 20, 30])
# append a single value
s1 = pd.concat([s1, pd.Series([40])])
# append a list of values
s1 = pd.concat([s1, pd.Series([50, 60, 70])])
# append another series
s2 = pd.Series([80, 90, 100])
s1 = pd.concat([s1, s2])
print(s1)
Output:
0 10
1 20
2 30
0 40
0 50
1 60
2 70
0 80
1 90
2 100
dtype: int64
Inserting an Element into a Series at a Specific Position
In scenarios where you want to insert an element at a specific position in a Series, you can use the loc indexer with a fractional index and then sort and reset the indices.
Example
Suppose we have a Series called fruits containing the following elements: apple, banana, and orange. Here’s how we can insert a new element pear after the second element banana in the Series:
import pandas as pd
fruits = pd.Series(["apple", "banana", "orange"])
# insert new element with a fractional index
fruits[1.5] = "pear"
# sort and reset index
fruits = fruits.sort_index().reset_index(drop=True)
print(fruits)
Output:
0 apple
1 banana
2 pear
3 orange
dtype: object
If you don’t sort and reset the indices, the newly inserted element won’t be at your desired position. This step is important but often overlooked.