【问题标题】:Difference between df.loc['col name'], df.loc[index]['col name'] and df.loc[index, 'col name'] in pandas?pandas 中 df.loc['column name']、df.loc[index]['column name'] 和 df.loc[index,'col name'] 的区别?
【发布时间】:2017-06-14 17:15:29
【问题描述】:

我有一个数据框df,其列名为“Store”。如果我想检索该列,以下几行同样适用 - df['Store'] 或 df[:]['Store'] 或 df[:,'Store']。

两者有什么区别?应该使用一个而不是另一个?

谢谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    df.loc[index, 'col name'] 更惯用且更受欢迎,尤其是在您想过滤行时

    演示:适用于 1.000.000 x 3 形状的 DF

    In [26]: df = pd.DataFrame(np.random.rand(10**6,3), columns=list('abc'))
    
    In [27]: %timeit df[df.a < 0.5]['a']
    10 loops, best of 3: 45.8 ms per loop
    
    In [28]: %timeit df.loc[df.a < 0.5]['a']
    10 loops, best of 3: 45.8 ms per loop
    
    In [29]: %timeit df.loc[df.a < 0.5, 'a']
    10 loops, best of 3: 37 ms per loop
    

    对于只需要一列并且不过滤像df[:]['Store'] 这样的行的结构 - 最好只使用df['Store']:

    In [30]: %timeit df[:]['a']
    1000 loops, best of 3: 436 µs per loop
    
    In [31]: %timeit df.loc[:]['a']
    10000 loops, best of 3: 25.9 µs per loop
    
    In [36]: %timeit df['a'].loc[:]
    10000 loops, best of 3: 26.5 µs per loop
    
    In [32]: %timeit df.loc[:, 'a']
    10000 loops, best of 3: 126 µs per loop
    
    In [33]: %timeit df['a']
    The slowest run took 5.08 times longer than the fastest. This could mean that an intermediate result is being cached.
    100000 loops, best of 3: 8.17 µs per loop
    

    无条件访问多列:

    In [34]: %timeit df[['a','b']]
    10 loops, best of 3: 22 ms per loop
    
    In [35]: %timeit df.loc[:, ['a','b']]
    10 loops, best of 3: 22.6 ms per loop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      相关资源
      最近更新 更多