Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to append elements to a Pandas series?
In Pandas, you can append elements to a Series using the append() method or the newer concat() function. The append() method allows you to combine two Series, but note that it's deprecated in newer Pandas versions in favor of concat().
Using append() Method
The traditional approach uses the append() method to combine Series ?
import pandas as pd
s1 = pd.Series([10, 20, 30, 40, 50])
s2 = pd.Series([11, 22, 33, 44, 55])
print("S1:")
print(s1)
print("\nS2:")
print(s2)
appended_series = s1.append(s2)
print("\nFinal Series after appending:")
print(appended_series)
S1: 0 10 1 20 2 30 3 40 4 50 dtype: int64 S2: 0 11 1 22 2 33 3 44 4 55 dtype: int64 Final Series after appending: 0 10 1 20 2 30 3 40 4 50 0 11 1 22 2 33 3 44 4 55 dtype: int64
Using concat() Method (Recommended)
The modern approach uses pd.concat() which is more flexible and efficient ?
import pandas as pd
s1 = pd.Series([10, 20, 30, 40, 50])
s2 = pd.Series([11, 22, 33, 44, 55])
# Using concat instead of append
appended_series = pd.concat([s1, s2])
print("Using concat():")
print(appended_series)
# Reset index to get continuous numbering
appended_reset = pd.concat([s1, s2], ignore_index=True)
print("\nWith reset index:")
print(appended_reset)
Using concat(): 0 10 1 20 2 30 3 40 4 50 0 11 1 22 2 33 3 44 4 55 dtype: int64 With reset index: 0 10 1 20 2 30 3 40 4 50 5 11 6 22 7 33 8 44 9 55 dtype: int64
Appending Individual Elements
You can also append individual elements by creating a new Series ?
import pandas as pd
original_series = pd.Series([1, 2, 3, 4])
new_element = pd.Series([5])
# Append single element
result = pd.concat([original_series, new_element], ignore_index=True)
print("Original series with new element:")
print(result)
Original series with new element: 0 1 1 2 2 3 3 4 4 5 dtype: int64
Key Points
- The
append()method is deprecated in Pandas 1.4.0+ - Use
pd.concat()for combining Series - Use
ignore_index=Trueto reset the index numbering - Both methods return a new Series without modifying the original
Conclusion
Use pd.concat() instead of append() for combining Pandas Series. The concat() method is more efficient and is the recommended approach in modern Pandas versions.
Advertisements
