python - 设置多索引系列的多个层

标签 python pandas series multi-index

TLDR:如何按任意切片在多级列表中设置值。我让它在最外面的切片上工作,但如果你沿着“中间”,就不行了

假设您有一个 2 层或 3 层多索引系列,如下所示:

_s01_|_s02_|_s03_|____
 'a' | 'c' | 'n' | 0.0
           | 'm' | 0.1
           | 'o' | 0.2
     | 'd' | 'n' | 0.3
           | 'o' | 0.4
 'b' | 'c' | 'n' | 0.5
        .........

这是我目前正在尝试做的事情:

r = pd.Series(0,index - data.index) #so create a similar structure
for i in data.index.levels[1]:
    d = data.loc[(slice(None),i,slice(None)]
    #manipulate values in d
    r.loc[(slice(None),i,slice(None)] = d

这只是将切片后的所有 r 值设置为 NaN

是否有通用的方法来查看多级索引系列并设置值?我正在尝试使用 DataFrame 进行非常类似的操作,导致相同问题的问题是 .loc 正在降低级别,然后索引不一样。我通过将语法修改为现在尝试与系列一起使用的语法解决了该问题。

任何帮助将不胜感激

最佳答案

Pandas 建议使用 pd.IndexSlice 或类似语法而不是 slice()。 (查看更多documentation on slicers here.),例如

明确:

idx = pd.IndexSlice
series.loc[idx[:, 'c', :]]

如果您只是想获取所选行的整个条目,则可以省略 idx 步骤快捷方式:series.loc[:, 'c', :] (这本质上就是简单索引所发生的情况。)

但是,最好使用 pd.IndexSlice,如果您尝试在 Dataframe 中建立索引,则更有必要使用 pd.IndexSlice。

假设我们有您的系列

series

>  s01  s02  s03
a    c    n      1
          m      0
          o      4
     d    n      6
          o      9
b    c    n      4
dtype: float64

在 pd.Series 和 pd.Dataframe 中建立多级索引的索引

关键部分

要建立索引,我们需要首先对系列索引进行词法排序:

series.sort_index(inplace = True)

然后,要进行任何索引,我们需要一个 pd.IndexSlice 对象,它通过以下方式定义 .loc 的选择:

idx = pd.IndexSlice
# do your indexing
series.loc[idx[:,'c',:]]

详细信息

如果没有 pd.IndexSlice,多级索引上的索引将无法工作:

关于系列:

series.loc[[:,'c',:]]` will give you:

File "<ipython-input-101-21968807c1d1>", line 1
    df.loc[[:,'c',:]]
        ^
SyntaxError: invalid syntax


# with IndexSlice
idx = pd.IndexSlice
series.loc[idx[:,'c',:]]

>  s01  s03
a    n      1
     m      0
     o      4
b    n      4
dtype: int64

如果我们有一个 pd.DataFrame,我们会做类似的事情。

假设我们有以下 pd.Dataframe:

df
>              hello animal   i_like
s01 s02 s03                       
a   c   m        0  Goose  dislike
        n        1  Panda     like
        o        4  Tiger     like
    d   n        6  Goose     like
        o        9   Bear  dislike
b   c   n        4   Dog  dislike

到索引:

df.sort_index(inplace = True) # need to lexsort for indexing

# without pd.IndexSlice
df.loc[:,'c',:]   # the whole entry 
File "<ipython-input-118-9544c9b9f9da>", line 1
df.loc[(:,'c',:)]
        ^
SyntaxError: invalid syntax

# with pd.IndexSlice
idx = pd.IndexSlice
df.loc[idx[:,'c',:],:]

>             hello animal   i_like
s01 s02 s03                       
a   c   m        0  Goose  dislike
        n        1  Panda     like
        o        4  Tiger     like
b   c   n        4   Dog  dislike

以及特定列

df.loc[idx[:,'d',:],['hello','animal']]

>              hello animal
s01 s02 s03              
a   d   n        6  Goose
        o        9   Bear

设置值

如果您想为您的选择设置值,您可以照常进行:

对于一个系列:

my_select = series.loc[idx[:,'c',:],:]
series.loc[idx[:,'c',:]] = my_select.apply(lambda x: x*3)

series
> s01  s02  s03
a    c    m       0
          n       3
          o      12
     d    n       6
          o       9
b    c    n      12
dtype: int64

对于数据框:

my_select = df.loc[idx[:,'d',:],:]
df.loc[idx[:,'d',:],['i_like']] = my_select.apply(
      lambda x: "dislike" if x.hello<5 else "like", axis=1)

df
>             hello animal   i_like
s01 s02 s03                       
a   c   m        0  Goose  dislike
        n        1  Panda  dislike
        o        4  Tiger     like
    d   n        6  Goose     like
        o        9   Bear  dislike
b   c   n        4   Dog     like

# Panda is changed to "dislike", and Dog to "like". 
PS。注意逗号/冒号(或缺少逗号/冒号)!

希望这有帮助!

关于python - 设置多索引系列的多个层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44166176/

相关文章:

python - 使用 Tkinter Python 的简单动画

python - 如何在 Pandas 列中查找并提取字符串的一部分并将其编码到新列中

python - 使用索引列表访问 pandas 数据框中的条目

python - 将两列等长合并为一列

python - 如何检查 pandas 数据框是否仅按列包含数值?

python - 在 Python 中创建实例方法对象的不同方式

python - 为什么在 Python 中使用 .writelines() 时会在字符串末尾添加 'i' 字符?

python - matplotlib/seaborn : first and last row cut in half of heatmap plot

计算条件均值和方差的Python方法?

python - 从python中的 Pandas 系列中删除元素