如何在 pandas 中使用多索引迭代系列
how to iterate a Series with multiindex in pandas
我是 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
然后我分组 'Peanut' 和 'Chocolate',我得到的是:
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 的值,但无法获取 'Peanut' 和 'Chocolate.如何同时获取 serie1 的数量以及 'Peanut' 和 'Chocolate 的值?
您可以使用 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'])
您可以获得列名和级别的值。请注意,标签引用级别中同一行中的索引。例如,对于 'Peanut',第一个标签是 levels[0][labels[0][0]]
,即 'N'。 'Chocolate' 的最后一个标签是 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 实现决策树算法。首先,我将测试数据读入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
然后我分组 'Peanut' 和 'Chocolate',我得到的是:
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 的值,但无法获取 'Peanut' 和 'Chocolate.如何同时获取 serie1 的数量以及 'Peanut' 和 'Chocolate 的值?
您可以使用 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'])
您可以获得列名和级别的值。请注意,标签引用级别中同一行中的索引。例如,对于 'Peanut',第一个标签是 levels[0][labels[0][0]]
,即 'N'。 'Chocolate' 的最后一个标签是 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