Search code examples
pythonpandasdataframevalueerror

python pandas DataFrame - assign a list to multiple cells


I have a DataFrame like

name col1 col2
 a    aa   123
 a    bb   123
 b    aa   234

and a list

[1, 2, 3]

I want to replace the col2 of every row with col1 = 'aa' with the list like

name col1     col2
 a    aa   [1, 2, 3]
 a    bb       123
 b    aa   [1, 2, 3]

I tried something like

df.loc[df[col1] == 'aa', col2] = [1, 2, 3]

but it gives me the error:

ValueError: could not broadcast input array from shape (xx,) into shape (yy,)

How should I get around this?


Solution

  • import pandas as pd
    df = pd.DataFrame({"name":["a","a","b"],"col1":["aa","bb","aa"],"col2":[123,123,234]})
    l = [1,2,3]
    df["col2"] = df.apply(lambda x: l if x.col1 == "aa" else x.col2, axis =1)
    df