python pandas loc 函数的使用详解

19 min read

pandas库中的loc函数是用于获取和修改数据的函数之一。它的用法如下:

loc函数的基本语法是df.loc[row_indexer, column_indexer],其中df是一个DataFrame对象,row_indexercolumn_indexer是用于选择行和列的标签、布尔值或切片。

下面是关于loc函数使用的详解:

  1. 选择行和列:

    • 如果只给定行索引器,那么将返回具有该行索引的所有列的数据:
      df.loc[row_indexer]
      
    • 如果同时给定行和列索引器,那么将返回具有指定行和列的数据:
      df.loc[row_indexer, column_indexer]
      
    • 可以使用整数索引器、标签索引器、布尔索引器或切片索引器进行选择。
    • 可以使用多个行和列索引器,例如:
      df.loc[[row_indexer1, row_indexer2], [column_indexer1, column_indexer2]]
      
    • 可以使用切片索引器选择多行或多列,例如:
      df.loc[row_indexer1:row_indexer2, column_indexer1:column_indexer2]
      
    • 可以使用布尔索引器选择满足某个条件的行或列,例如:
      df.loc[df['column_name'] > 5, ['column_name1', 'column_name2']]
      
  2. 修改数据:

    • 可以使用loc函数修改某个单元格的值,例如:
      df.loc[row_indexer, column_indexer] = new_value
      
      这将把某个单元格的值修改为new_value
    • 可以使用loc函数批量修改某些单元格的值,例如:
      df.loc[row_indexer, column_indexer] = [new_value1, new_value2, ...]
      
      这将把某些单元格的值修改为new_value1, new_value2, ...
  3. 条件和过滤操作:

    • 可以使用布尔索引器选择满足某个条件的行或列,例如:
      df.loc[df['column_name'] > 5]
      
    • 可以使用布尔索引器选择满足多个条件的行或列,例如:
      df.loc[(df['column_name1'] > 5) & (df['column_name2'] == 'value')]
      

总结:
loc函数是pandas库中用于获取和修改数据的重要函数之一。它可以选择指定的行和列,并且可以使用整数索引器、标签索引器、布尔索引器或切片索引器进行选择。此外,loc函数还支持条件过滤和修改数据的操作。