使用多索引数据框复制.get()功能

时间:2018-03-07 01:21:21

标签: python pandas dataframe

我需要将一些代码从字典转换为数据帧。如何复制字典的功能.get()?我的主要功能是什么,但我无法弄清楚如何使默认值有效。例如,在下面的代码中,数据框的输出应包含234的index1值。(由于各种原因,我无法更改传入数据的格式。)

                0
index1 index2    
123    12      65
       6544    44
       23423   66
234    725     42
       7245    62

{234: 999, 123: 65}

                0
index1 index2    
123    12      65

结果:

def dataframe_get(df, index2, default_value=0):
    levels = df.index.levels[:-1] + [[index2]]
    new_index = pandas.MultiIndex.from_product(levels, names=["index1", "index2"])
    data = df.reindex(new_index)
    return data.loc(axis=0)[:, index2].fillna(default_value)
编辑:我得到了一些东西:

index1 index2       
123    12       65.0
234    12      999.0

这几乎是正确的,但我需要删除index2;我还在努力。

// You MUST send a subscription request first! Otherwise there won't be
// any cookies to examine.
exchangeService.SubscribeToStreamingNotifications(foldersToSubscribeTo, EventsToSubscribeTo);

// Get a string of all the cookies
var allCookies = exchangeService.CookieContainer.GetCookieHeader(exchangeService.Url);
Console.WriteLine(allCookies);

// Or get a specific cookie
var cookies = exchangeService.CookieContainer.GetCookies(exchangeService.Url);
var xBackEndOverrideCookie = cookies["X-BackEndOverrideCookie"];
Console.WriteLine(XBackEndOverrideCookie);

1 个答案:

答案 0 :(得分:0)

好的,让这个工作:

def dataframe_get(df, index2, default_value=0):
    index_length = len(df.index.levels)
    levels = df.index.levels[:-1] + [[index2]]
    new_index = pandas.MultiIndex.from_product(levels, names=["index1", "index2"])
    data = df.reindex(new_index)
    data.index = data.index.droplevel(index_length - 1)
    return data.fillna(default_value)