如何在pandas中获得索引列表的并集?我有以下内容,但有更优雅的方式吗?
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)
答案 0 :(得分:0)
参考this post,您可以进行一些小修改并尝试
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])
不确定你是否认为它更优雅,但它确实存在。