Search code examples
pythonpandasmulti-index

Pandas: assign a list to all rows of a multi-index dataframe


I have a multi index dataframe, let's say

index = [['a', 'a', 'b', 'b'],[1, 2, 1, 2]]
df = pd.DataFrame([1,2,3,4], index=index)

     0
a 1  1
  2  2
b 1  3
  2  4

If I want to add a new column with a constant value, I can just do

df['new_col'] = 'IamNew'

     0 new_col
a 1  1  IamNew
  2  2  IamNew
b 1  3  IamNew
  2  4  IamNew

Perfect. However, what if I want to add a new column with a list? This doesn't work

df['new_col']=[1,2]
ValueError: Length of values does not match length of index

I have tried many options and spent quite some time trying to figure this out. Any idea?


Solution

  • First I think working with lists in pandas is not good idea, but possible:

    df['new_col']=pd.Series([[1,2]] * len(df), index=df.index)
    print (df)
         0 new_col
    a 1  1  [1, 2]
      2  2  [1, 2]
    b 1  3  [1, 2]
      2  4  [1, 2]
    

    Another solution:

    df['new_col']= [[1,2]] * len(df)