pandas - 如何在 pandas 中使用多索引迭代系列

标签 pandas series multi-index

我是 Pandas 的初学者。现在我想用pandas实现决策树算法。首先,我将测试数据读入 padas.DataFrame,如下所示:

In [4]: df = pd.read_csv('test.txt', sep = '\t')

In [5]: df
Out[5]:
  Chocolate Vanilla Strawberry Peanut
0         Y       N          Y      Y
1         N       Y          Y      N
2         N       N          N      N
3         Y       Y          Y      Y
4         Y       Y          N      Y
5         N       N          N      N
6         Y       Y          Y      Y
7         N       Y          N      N
8         Y       N          Y      N
9         Y       N          Y      Y

然后我将“花生”和“巧克力”分组,得到的是:

In [15]: df2 = df.groupby(['Peanut', 'Chocolate'])

In [16]: serie1 = df2.size()

In [17]: serie1
Out[17]:
Peanut  Chocolate
N       N            4
        Y            1
Y       Y            5
dtype: int64

现在,serie1 的类型是 Series。我可以访问 serie1 的值,但无法获取“花生”和“巧克力”的值。如何同时获取 serie1 的编号以及“花生”和“巧克力”的值?

最佳答案

您可以使用index :

>>> serie1.index
MultiIndex(levels=[[u'N', u'Y'], [u'N', u'Y']],
           labels=[[0, 0, 1], [0, 1, 1]],
           names=[u'Peanut', u'Chocolate'])

您可以获得列名和级别的值。请注意,标签指的是级别中同一行的索引。例如,对于“花生”,第一个标签是 levels[0][labels[0][0]]这是“N”。 “巧克力”的最后一个标签是 levels[1][labels[1][2]]这是“Y”。

我创建了一个小示例,它循环遍历索引并打印所有数据:

#loop the rows
for i in range(len(serie1)):
   print "Row",i,"Value",serie1.iloc[i],
   #loop the columns
   for j in range(len(serie1.index.names)):
      print "Column",serie1.index.names[j],"Value",serie1.index.levels[j][serie1.index.labels[j][i]],
   print

结果是:

Row 0 Value 4 Column Peanut Value N Column Chocolate Value N
Row 1 Value 1 Column Peanut Value N Column Chocolate Value Y
Row 2 Value 5 Column Peanut Value Y Column Chocolate Value Y

关于pandas - 如何在 pandas 中使用多索引迭代系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34072324/

相关文章:

python - 在 pandas 中使用元组作为索引键时如何返回 "explicitly specify the categories order by passing in a categories argument"?

python - 在 pandas DataFrame 多索引函数之外解压列表

python - 使用 hexbin 的 Pairplot

python - pandas 系列 groupby 一组

python - 制作 Pandas 系列的直方图

python - 如何从 Pandas 的几列中删除不同的字符串

c++ - boost::multi_index 复合键效率

python - 如何在python中合并两个不规则的数据框

pandas - 在 pandas 中使用 from_records 时出现断言错误

python - 具有已建立范围的第一个值的新列