代码之家  ›  专栏  ›  技术社区  ›  Konstantin

pandas dataframe.loc中的不同括号[重复]

  •  1
  • Konstantin  · 技术社区  · 7 年前

    用起来有什么不同 loc[x,y] VS loc[x][y] VS loc[[x]][y] ?乍一看,它们似乎很相似。

    df = pd.DataFrame(np.arange(6).reshape(3, 2),
                      columns=['price', 'count'],
                      index=['First', 'Second', 'Third'])
    print(df)
    #         price  count
    # First       0      1
    # Second      2      3
    # Third       4      5
    
    print(df.loc['Second', 'count'])
    # 3
    
    print(df.loc['Second']['count'])
    # 3
    
    print(df.loc[['Second'], 'count'])
    # Second    3
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   EdChum Arthur G    7 年前

    虽然前2个在输出中是等效的,但第二个被称为链接索引:

    http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

    类型也为 Series 对于第二个:

    In[48]:
    type(df.loc['Second'])
    
    Out[48]: pandas.core.series.Series
    

    然后索引索引索引值,然后返回标量值:

    In[47]:
    df.loc['Second']
    
    Out[47]: 
    price    2
    count    3
    Name: Second, dtype: int32
    
    In[49]:
    df.loc['Second']['count']
    
    Out[49]: 3
    

    对于最后一个,附加括号返回一个df,这就是为什么您看到的是索引值而不是标量值:

    In[44]:
    type(df.loc[['Second']])
    
    Out[44]: pandas.core.frame.DataFrame
    

    因此,然后传递该列,对该df进行索引,并返回匹配的列,作为 系列 :

    In[46]:
    type(df.loc[['Second'],'count'])
    
    Out[46]: pandas.core.series.Series
    

    因此,这取决于您想要实现什么,但要避免使用第二种形式,因为当试图分配给列或df时,它可能会导致意外的行为。

    推荐文章