rsmith54
rsmith54

Reputation: 805

Union of a list of indices

How do I get the union of a list of indices in pandas? I have the following, but is there a more elegant way?

import pandas as pd

def union_list_indices( list_of_indices):
    new_index = pd.Index([])
    for index in list_of_indices:
        new_index = new_index.union(index)
    return(new_index)

Upvotes: 2

Views: 1341

Answers (1)

Amw 5G
Amw 5G

Reputation: 689

Referring to this post, you could do a small modification and try

from operator import or_ as union
from functools import reduce
import pandas as pd

df_a = pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
                        orient='index', columns=['one', 'two', 'three'])
df_b = pd.DataFrame.from_items([('C', [7, 8, 9]), ('D', [10, 11, 12])],
                        orient='index', columns=['one', 'two', 'three'])
df_c = pd.DataFrame.from_items([('E', [7, 8, 9]), ('F', [10, 11, 12])],
                        orient='index', columns=['one', 'two', 'three'])

def idx_union(mylist):
    idx = reduce(union, (index for index in mylist))
    return idx

bar = idx_union([df_a.index, df_b.index, df_c.index])   

Not sure if you consider it more elegant, but it's something.

Upvotes: 4

Related Questions