python - Pandas Multiindex 从索引的第一个条目中获取值

标签 python pandas multi-index

我有以下多索引数据框:

from io import StringIO
import pandas as pd
datastring = StringIO("""File,no,runtime,value1,value2
    A,0, 0,12,34
    A,0, 1,13,34
    A,0, 2,23,34
    A,1, 6,23,38
    A,1, 7,22,38
    B,0,17,15,35
    B,0,18,17,35
    C,0,34,23,32
    C,0,35,21,32
    """)    
df = pd.read_csv(datastring, sep=',')
df.set_index(['File','no',df.index], inplace=True)


>> df
               runtime  value1  value2
File   no               
A      0    0     0       12      34
            1     1       13      34
            2     2       23      34
       1    3     6       23      38
            4     7       22      38
B      0    5     17      15      35
            6     18      17      35
C      0    7     34      23      32
            8     35      21      32

我想得到的只是带有新文件和不同编号的每个条目的第一个值

A 0 34
A 1 38
B 0 35
C 0 32

我能在这些地方找到最相似的问题

Resample pandas dataframe only knowing result measurement count

MultiIndex-based indexing in pandas

Select rows in pandas MultiIndex DataFrame

但我无法从中构建解决方案。我得到的最好结果是 ix 操作,但由于技术上的值仍然存在(只是没有显示),结果是

idx = pd.IndexSlice
df.loc[idx[:,0],:]

例如,可以过滤 0 值,但仍会返回数据帧的整个其余部分。

多索引是否是完成手头任务的正确工具?如何解决?

最佳答案

使用GroupBy.first通过 MultiIndex 的第一级和第二级:

s = df.groupby(level=[0,1])['value2'].first()
print (s)
File  no
A     0     34
      1     38
B     0     35
C     0     32
Name: value2, dtype: int64

如果需要一列DataFrame使用一个元素list:

df1 = df.groupby(level=[0,1])[['value2']].first()
print (df1)
         value2
File no        
A    0       34
     1       38
B    0       35
C    0       32

另一个想法是通过 DataFrame.reset_index 删除 3rd 级别并按 Index.get_level_values 过滤与 boolean indexing :

df2 = df.reset_index(level=2, drop=True)
s = df2.loc[~df2.index.duplicated(), 'value2']
print (s)
File  no
A     0     34
      1     38
B     0     35
C     0     32
Name: value2, dtype: int64

关于python - Pandas Multiindex 从索引的第一个条目中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57076657/

相关文章:

python - 如何删除出现在整数列中的垃圾字符串

python - 遵循层次结构的多个嵌套字典

python - 使用 Pandas 绘制多索引表中的特定列

python - 按位置切片 MultiIndex pandas DataFrame

c++ - 使用 Boost Multi-Index 搜索多个索引

python - gensim.corpora.Dictionary 是否保存了词频?

python - 在 python 中编写模块化代码

python - 为什么索引超出范围的子字符串切片有效?

python - Pandas 将函数应用于列的子集以创建新列

python - 尝试从 Python BS 中的网站抓取表格时出现 AttributeError