Pandas-数据选取

Pandas包对数据的常用数据切片功能

目录


DataFrame的索引选取

  • []
    • 只能对行进 行(row/index) 切片,前闭后开
      df[0:3]
      df[:4]
      df[4:]
  • where 布尔查找
    • 在[]基础上的运用  
      df[df["A"]>7]
  • isin
    • 比where更为灵活
      # 返回布尔值
      s.isin([1,2,3])
      df["A"].isin([1,2,3])
      
      df.loc[df['sepal_length'].isin([5.8,5.1])]
  • query
    • 多个where整合切片,&:于,|:或  
      df.query(" A>5.0 & (B>3.5 | C<1.0) ")
  • loc :根据名称Label切片
    • 切名称
      # df.loc[A,B] A是行范围,B是列范围
      df.loc[1:4,['petal_length','petal_width']]
    • 创建新变量
      # 需求1:创建一个新的变量 test
      # 如果sepal_length > 3 test = 1 否则 test = 0
      df.loc[df['sepal_length'] > 6, 'test'] = 1
      df.loc[df['sepal_length'] <=6, 'test'] = 0
      
      # 需求2:创建一个新变量test2 
      # 1.petal_length>2 and petal_width>0.3 = 1 
      # 2.sepeal_length>6 and sepal_width>3 = 2 3.其他 = 0
      df['test2'] = 0
      df.loc[(df['petal_length']>2)&(df['petal_width']>0.3), 'test2'] = 1
      df.loc[(df['sepal_length']>6)&(df['sepal_width']>3), 'test2'] = 2
  • iloc:切位置
    • 切位置,以序列号去切
      df.iloc[1:4,:]
  • ix:混切
    • 名称和位置混切,但效率低,少用
      df1.ix[0:3,['sepal_length','petal_width']]
  • map与lambda
    •   
      alist = [1,2,3,4]
      map(lambda s : s+1, alist)
      [2, 3, 4, 5]
    • df['sepal_length'].map(lambda s:s*2+1)[0:3]
      0    11.2
      1    10.8
      2    10.4
      Name: sepal_length, dtype: float64
  •  contains
    • # 使用DataFrame模糊筛选数据(类似SQL中的LIKE)
      # 使用正则表达式进行模糊匹配,*匹配0或无限次,?匹配0或1次
      df_obj[df_obj['套餐'].str.contains(r'.*?语音CDMA.*')] 

      # 下面两句效果一致
      df[df['商品名称'].str.contains("四件套")]
      df[df['商品名称'].str.contains(r".*四件套.*")]

原文地址:https://www.cnblogs.com/stream886/p/5948728.html