Pandas Index.append() - Python
Index.append() method in Pandas is used to concatenate or append one Index object with another Index or a list/tuple of Index objects, returning a new Index object. It does not modify the original Index. Example:
import pandas as pd
idx1 = pd.Index([1, 2, 3])
idx2 = pd.Index([4, 5])
res = idx1.append(idx2)
print(res)
Output
Index([1, 2, 3, 4, 5], dtype='int64')
Explanation: Two Pandas Index objects, idx1 and idx2, are created. The .append() method combines them into a new Index stored in res, confirming that both Index objects have been successfully merged.
Syntax
Index.append(other, verify_integrity=False)
Parameters:
- other: Index or list/tuple of Index objects to append.
- verify_integrity (bool, optional): If True, checks for duplicate entries and raises ValueError if found. Default is False.
Returns: A new Index object with elements of other appended.
Examples
Example 1: In this example, three Index objects with string values are created and merged into one.
import pandas as pd
idx1 = pd.Index(['a', 'b'])
idx2 = pd.Index(['c'])
idx3 = pd.Index(['d', 'e'])
res = idx1.append([idx2, idx3])
print(res)
Output
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
Explanation: Three Pandas Index objects, idx1, idx2 and idx3, are created with string values. The .append() method is used to merge idx2 and idx3 into idx1, resulting in a new combined Index.
Example 2: In this example, two Index objects with integer values are created and merged using the .append() method. Duplicates are allowed by default and retained in the result.
import pandas as pd
idx1 = pd.Index([10, 20])
idx2 = pd.Index([20, 30])
res = idx1.append(idx2)
print(res)
Output
Int64Index([10, 20, 20, 30], dtype='int64')
Explanation: Two Pandas Index objects, idx1 and idx2, are merged using .append(), which allows duplicates by default. Since verify_integrity is no longer supported, values like 20 are retained without error.
Example 3: This example demonstrates how to manually prevent duplicate entries when merging Index objects.
import pandas as pd
idx1 = pd.Index([1, 2])
idx2 = pd.Index([2, 3])
res = idx1.append(idx2)
if res.has_duplicates:
raise ValueError(f"Indexes have overlapping values: {res[res.duplicated()].unique().tolist()}")
Output
ValueError: Indexes have overlapping values: [2]
Explanation: Two Pandas Index objects, idx1 and idx2, are merged using .append(). To prevent duplicates, a manual check using has_duplicates is performed and a ValueError is raised if any are found.