Pandas: 添加多索引 Series/Dataframes 包含列表

Pandas: adding multiindex Series/Dataframes containing lists

如何添加/合并两个包含列表作为元素的多索引 Series/DataFrames(在我的例子中是端口序列或时间戳序列)。特别是,如何处理只出现在一个 Series/DataFrame 中的索引?不幸的是,.add() 方法只允许 fill_value 参数的浮点数,而不是空列表。

我的数据:

print series1
print series2

IP               sessionID
195.12*.21*.11*  49                    [5900]
                 50         [5900, 5900, 5900, 5900, ...

IP               sessionID
85.15*.24*.12*   63                    [3389]
91.20*.4*.14*    68           [445, 445, 139]
113.9*.4*.16*    75                 [23, 210]
195.12*.21*.11*  49                    [5905]

预期结果:

IP               sessionID
195.12*.21*.11*  49              [5900, 5905]
                 50         [5900, 5900, 5900, 5900, ...
85.15*.24*.12*   63                    [3389]
91.20*.4*.14*    68           [445, 445, 139]
113.9*.4*.16*    75                 [23, 210]

奇怪的是,series1.add(series1)series2.add(series2) 确实可以正常工作并按预期附加列表,但是 series1.add(series2) 会产生运行时错误。 series1.combine_first(series2) 有效,但它不会合并列表 - 它只需要一个。有什么想法吗?

是的,我知道列表作为元素是不好的风格,但这就是我的数据现在的方式。对不起。为了简短起见,我刚刚发布了系列示例,如果您还需要 DataFrame 示例,请告诉我。

以防万一那里有任何其他可怜的幽灵需要此信息... 这似乎是一个肮脏的解决方法,但它有效:

# add() works for mutual indices, so find intersection and call it
# fortunately, it appends list2 to list1!
intersection = series1.index.intersection(series2.index)
inter1 = series1[series1.index.isin(intersection)]
inter2 = series2[series2.index.isin(intersection)]
interAppend = inter1.add(inter2)

# combine_first() unions indices and keeps the values of the caller,
# so it will keep the appended lists on mutual indices,
# while it adds new indices and corresponding values
exclusiveAdd = interAppend.combine_first(series1).combine_first(series2)