dynamic underscore selector #6921
              
                
                  
                  
                    Answered
                  
                  by
                    gforsyth
                  
              
          
                  
                    
                      ozgurkalan
                    
                  
                
                  asked this question in
                Q&A
              
            -
| Hi, How to make a dynamic selection for the underscore ( _ ), especially during aggregation. sample: some_var = "quantity"
(t
.aggregate(_.[some_var].sum(), by="year")
)
 | 
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            gforsyth
          
      
      
        Aug 23, 2023 
      
    
    Replies: 1 comment 3 replies
-
| Hey @ozgurkalan -- there are a few ways you can do this: 
 [ins] In [23]: var
Out[23]: 'bill_length_mm'
[ins] In [24]: penguins.aggregate(getattr(_, var).sum(), by="year")
Out[24]: 
┏━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓
┃ year  ┃ Sum(bill_length_mm) ┃
┡━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩
│ int64 │ float64             │
├───────┼─────────────────────┤
│  2007 │              4767.7 │
│  2008 │              4963.7 │
│  2009 │              5289.9 │
└───────┴─────────────────────┘
 [ins] In [25]: import ibis.selectors as s
[ins] In [26]: var
Out[26]: 'bill_length_mm'
[ins] In [27]: penguins.aggregate(s.across(s.c(var), _.sum()), by="year")
Out[27]: 
┏━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ year  ┃ bill_length_mm ┃
┡━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ int64 │ float64        │
├───────┼────────────────┤
│  2007 │         4767.7 │
│  2008 │         4963.7 │
│  2009 │         5289.9 │
└───────┴────────────────┘I'd suggest the selector approach, as it is more flexible and will lend itself more readily to selecting multiple columns in a dynamic way. | 
Beta Was this translation helpful? Give feedback.
                  
                    3 replies
                  
                
            
      Answer selected by
        ozgurkalan
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
Hey @ozgurkalan -- there are a few ways you can do this:
getattrfor grabbing the column name associated with your variable: