Pandas - 在整数轴上按位置正确索引,在另一轴上正确标记(以避免链接赋值)

use*_*588 6 python pandas

我知道大熊猫提供:

  1. .ix - 混合标签和位置索引(主要是标签),如果索引是整数 - 它将被解释为标签
  2. .loc - 按标签显式索引
  3. .iloc - 按位置显式索引

这很酷.

什么是通过标签(ala .loc)和按位置(ala .iloc)一次索引列的正确方法,以避免链式分配?优选地,它会避免reset_index().

为了提供示例,假设以下DataFrame df:

   col1  col2  col3
3     1     4     2
2     2     3     3
4     3     2     1
1     4     1     4
Run Code Online (Sandbox Code Playgroud)

大熊猫有类似的东西some_indexer,其行为如下?

In[2]: df.some_indexer[2,'col2':'col3']
Out[2]:
col2    2
col3    1
Name: 4, dtype: object
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 5

我知道这是一个老问题,但这确实可以在没有链式索引或使用reset_index(). 您只需要df.index[2].loc索引器内部使用。

df.loc[df.index[2],'col2':'col3']
Run Code Online (Sandbox Code Playgroud)

这也适用于作业。


EdC*_*ica 1

通常我们会这样做df.ix[2, 'col2':'col3'],但因为您的索引不明确,您会得到第二行而不是第三行,因为它2显示为位置 1 处索引中的值,因此标签选择成功,因为ix首先尝试标签选择,然后尝试位置选择。

来自文档:

.ix 支持混合整数和基于标签的访问。它主要是基于标签的,但除非相应的轴是整数类型,否则将回退到整数位置访问。.ix 是最通用的,支持 .loc 和 .iloc 中的任何输入。.ix 还支持浮点标签方案。.ix 在处理混合位置和基于标签的分层索引时特别有用。

In [246]:

df.ix[2,'col2':'col3']
Out[246]:
col2    3
col3    3
Name: 2, dtype: int64
Run Code Online (Sandbox Code Playgroud)

以下内容可行,但这是链式调用,并且分配可能会在副本上进行操作并引发警告:

In [247]:

df.iloc[2][['col2','col3']]
Out[247]:
col2    2
col3    1
Name: 4, dtype: int64
Run Code Online (Sandbox Code Playgroud)

最简单的事情是重置索引,然后您可以调用ix,我们必须再次删除索引,因为这是作为列插入的:

In [250]:

df = df.reset_index().drop('index',axis=1)
df
Out[250]:
   col1  col2  col3
0     1     4     2
1     2     3     3
2     3     2     1
3     4     1     4
In [251]:

df.ix[2,'col2':'col3']
Out[251]:
col2    2
col3    1
Name: 2, dtype: int64
Run Code Online (Sandbox Code Playgroud)