有时我正在处理具有数字索引的DataFrame
,但我想绕过它以根据它们的顺序引用行,
In [49]: df = pandas.DataFrame(np.random.randn(3, 5))
In [50]: df
Out[50]:
0 1 2 3 4
0 -2.426211 0.670384 0.545880 -1.435168 0.675598
1 0.507128 0.478832 -0.159536 -0.696284 -1.112171
2 0.938019 -1.673491 -0.567462 0.381804 -1.280602
In [51]: df[1:2]
Out[51]:
0 1 2 3 4
1 0.507128 0.478832 -0.159536 -0.696284 -1.112171
In [52]: df2 = df.ix[1:2]
In [53]: df2
Out[53]:
0 1 2 3 4
1 0.507128 0.478832 -0.159536 -0.696284 -1.112171
2 0.938019 -1.673491 -0.567462 0.381804 -1.280602
In [55]: df2.ix[0]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
...
In [56]: df2.rename(index={1: "one", 2:"two"})
Out[56]:
0 1 2 3 4
one 0.507128 0.478832 -0.159536 -0.696284 -1.112171
two 0.938019 -1.673491 -0.567462 0.381804 -1.280602
In [57]: df3 = df2.rename(index={1: "one", 2:"two"})
In [58]: df3.ix[0]
Out[58]:
0 0.507128
1 0.478832
2 -0.159536
3 -0.696284
4 -1.112171
Name: one
如何绕过pandas的索引来访问基础矩阵索引?
答案 0 :(得分:4)
您可以使用DataFrame.irow:
In [18]: df2
Out[18]:
0 1 2
1 2.279885 -0.414938 -2.230296
2 -0.237980 -0.219556 1.231576
In [19]: df2.irow(0)
Out[19]:
0 2.279885
1 -0.414938
2 -2.230296
Name: 1
In [20]: df2.irow([0, 1])
Out[20]:
0 1 2
1 2.279885 -0.414938 -2.230296
2 -0.237980 -0.219556 1.231576