Dynamically mutate a column #6936
              
                
                  
                  
                    Answered
                  
                  by
                    jcrist
                  
              
          
                  
                    
                      ozgurkalan
                    
                  
                
                  asked this question in
                Q&A
              
            -
| Hi, col = "Mkw2"
if col.startswith("Mkw"):
    t = t.mutate(..mutate..the..col...) | 
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            jcrist
          
      
      
        Aug 25, 2023 
      
    
    Replies: 2 comments 1 reply
-
| this is my workaround: col = "Mkw2"
    if col.startswith("Wkw"):
        t=(t
           .mutate(x=...some..mutate...)
           .drop(col)
           .relabel({"x":col})
          ) | 
Beta Was this translation helpful? Give feedback.
                  
                    1 reply
                  
                
            -
| No need to drop and relabel the column. You can control the name of the mutated columns using either the  In [1]: import ibis
In [2]: ibis.options.interactive = True
In [3]: from ibis import _
In [4]: t = ibis.memtable({"x": [1, 2, 3], "y": [-1, -2, -3]})
In [5]: t
Out[5]: 
┏━━━━━━━┳━━━━━━━┓
┃ x     ┃ y     ┃
┡━━━━━━━╇━━━━━━━┩
│ int64 │ int64 │
├───────┼───────┤
│     1 │    -1 │
│     2 │    -2 │
│     3 │    -3 │
└───────┴───────┘
In [6]: col = "y"
In [7]: t.mutate(_[col].abs().name(col))  # mutate col, and rename expr back to col
Out[7]: 
┏━━━━━━━┳━━━━━━━┓
┃ x     ┃ y     ┃
┡━━━━━━━╇━━━━━━━┩
│ int64 │ int64 │
├───────┼───────┤
│     1 │     1 │
│     2 │     2 │
│     3 │     3 │
└───────┴───────┘
In [8]: t.mutate(**{col: _[col].abs()})  # same thing, but using keywords as names
Out[8]: 
┏━━━━━━━┳━━━━━━━┓
┃ x     ┃ y     ┃
┡━━━━━━━╇━━━━━━━┩
│ int64 │ int64 │
├───────┼───────┤
│     1 │     1 │
│     2 │     2 │
│     3 │     3 │
└───────┴───────┘ | 
Beta Was this translation helpful? Give feedback.
                  
                    0 replies
                  
                
            
      Answer selected by
        ozgurkalan
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
No need to drop and relabel the column. You can control the name of the mutated columns using either the
.namemethod on a column expression, or by passing in the mutated columns via keywords as names.