title: How can I assign a new column to a slice of a pandas DataFrame with a multiindex?
body: <p>I have a pandas DataFrame with a multi-index like this:</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  
  arr = [1]*3 + [2]*3
  arr2 = list(range(3)) + list(range(3))
  mux = pd.MultiIndex.from_arrays([
      arr,
      arr2
  ], names=['one', 'two'])
  
  df = pd.DataFrame({'a': np.arange(len(mux))}, mux)
  df
  </code></pre>
  
  <pre><code>        a
  one two 
  1   0   0
  1   1   1
  1   2   2
  2   0   3
  2   1   4
  2   2   5
  </code></pre>
  
  <p>I have a function that takes a slice of a DataFrame and needs to assign a new column to the rows that have been sliced:</p>
  
  <pre><code>def work(df):
      b = df.copy()
  
      #do some work on the slice and create values for a new column of the slice
      b['b'] = b['a']*2
  
      #assign the new values back to the slice in a new column
      df['b'] = b['b']
  
  #pass in a slice of the df with only records that have the last value for 'two'
  work(df.loc[df.index.isin(df.index.get_level_values('two')[-1:], level=1)])
  </code></pre>
  
  <p>However calling the function results in the error:</p>
  
  <pre><code>SettingWithCopyWarning: 
  A value is trying to be set on a copy of a slice from a DataFrame.
  Try using .loc[row_indexer,col_indexer] = value instead
  
  See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
    # This is added back by InteractiveShellApp.init_path()
  </code></pre>
  
  <p>How can I create a new column 'b' in the original DataFrame and assign its values for only the rows that were passed to the function, leaving the rest of the rows nan?</p>
  
  <p>The desired output is:</p>
  
  <pre><code>        a   b
  one two 
  1   0   0   nan
  1   1   1   nan
  1   2   2   4
  2   0   3   nan
  2   1   4   nan
  2   2   5   10
  </code></pre>
  
  <p>NOTE: In the work function I'm actually doing a bunch of complex operations involving calling other functions to generate the values for the new column so I don't think this will work. Multiplying by 2 in my example is just for illustrative purposes.</p>