title: Adding a new pandas dataframe columns populating it with conditional calculations (mean if, standard deviation if)
body: <p>I need to add 2 columns to a Pandas data frame populated with conditional mean and standard deviation.</p>
  
  <pre><code># Import pandas library 
  import pandas as pd 
  
  # Initialize list of lists 
  data = [
      ['Tom',   'Blue', 'Small',  10, ], 
      ['Tom',   'Blue', 'Big',    15, ], 
      ['Tom',   'Red',  'Big',     3, ], 
      ['Tom',   'Red',  'Small',   8, ], 
      ['Tom',   'Red',  'Medium',  5, ], 
      ['Tom',   'Blue', 'Medium', 12, ], 
      ['Nick',  'Blue', 'Small',  15, ], 
      ['Nick',  'Red',  'Medium', 11, ], 
      ['Nick',  'Red',  'Small',  17, ], 
      ['Julie', 'Blue', 'Big',    14, ], 
      ['Julie', 'Red',  'Big',    11, ],
      ['Julie', 'Red',  'Medium',  3, ], 
      ['Julie', 'Red',  'Medium',  4, ],
  ]
  
  # Create the pandas DataFrame 
  df = pd.DataFrame(data, columns = ['Name', 'Colour', 'Size', 'Age']) 
  
  # print dataframe. 
  df
  </code></pre>
  
  <p>In this example, I need to add 2 columns:
  <code>df['mean']</code> and <code>df['std']</code> conditional to the name and colour only.</p>
  
  <p>I looked at <code>.mean()</code> and <code>.std()</code> documentation but didn't find a way to add a set of conditions. I believe I might need 2 functions that, for each row, takes the name and the colour as arguments, calculate the mean or std over the whole series, and then populate the new columns.</p>
  
  <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.std.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.std.html</a></p>
  
  <p>I believe I need a function that dynamically checks the name and the colour for each row, because, unlike this example data frame, my application is for a data frame that has thousands and names and thousands of colours.</p>
  
  <p>I know how to apply <code>.mean</code> or <code>.std</code> to a whole pandas series, without conditions:</p>
  
  <pre><code>df['Age'].std()
  </code></pre>
  
  <p>or</p>
  
  <pre><code>df['Age'].mean()
  </code></pre>
  
  <p>I also found that a group by + transformation does something slightly similar without the capacity to dynamically check for each row like a function could.</p>
  
  <pre><code>df['mean'] = df.groupby(['Name','Colour']).transform('mean')
  </code></pre>
  
  <p>Thank you for your help.</p>
  
  <p>Here is the output I expected. Thanks for the answers:
  <a href="https://i.stack.imgur.com/AfpD7.png" rel="nofollow noreferrer">Output dataframe</a></p>