【问题标题】:What are the pros/cons in using pd.Index vs df.loc使用 pd.Index 与 df.loc 的优缺点是什么
【发布时间】:2022-01-23 02:03:18
【问题描述】:

使用pd.Index 与df.loc 有什么区别?它实际上是同一件事吗?

idx = pd.Index(('a', 'b'))
df = pd.DataFrame({'a': [0, 1], 'b': [2, 3], 'c': [0, 5]})

print(df.loc[:, ('a', 'b')],)
print(df[idx])
a b
0 0 2
1 1 3

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    loc 如何成为首选方法是described in the documentation。使用多个切片可能会导致SettingWithCopyWarning:

    idx = ['a', 'b']
    d = df[idx]
    d.iloc[0,0] = 9
    
    SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame
    
    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
    

    相比之下,使用loc 不会触发SettingWithCopyWarning:

    idx = ['a', 'b']
    d = df.loc[:,idx]
    d.iloc[0,0] = 9
    

    值得注意的是,loc 还允许您将特定轴作为参数传递:

    df.loc(axis=1)[idx]
    

    【讨论】:

      【解决方案2】:

      当你做 loc 时,你可以做索引切片和列切片或组合,但是 pd.index 只能做列切片

      df.loc[[0]]
         a  b  c
      0  0  2  0
      
      df.loc[[0],['a','b']]
         a  b
      0  0  2
      

      IMO,loc 使用起来更灵活,我会选择loc,从长远来看会更清晰或检查后台。

      【讨论】:

      • 使用我一直在使用的数据框,我必须处理列组并跨所有行执行各种操作。所以我创建了一个 _index.py 模块,我将其作为 idx 导入,然后我可以调用组 df[idx.my_group1] ...
      • @JasonLeaver 您可以将它们存储在字典中〜
      猜你喜欢
      • 2010-12-03
      • 1970-01-01
      • 2017-07-26
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多