I wish to set a list of lists in a column (say "B") for a subset of rows. Suppose my dataframe (df) looks like below:
import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame({"A": np.random.randn(5)})
idx = df["A"] < 0
mylist = np.random.randint(0, 5, (idx.sum(), 3)).tolist()
df["B"] = None
First attempy was to do this which chucked an error: df.loc[idx, "B"] = mylist. The next attempt df.loc[idx, "B"] = pd.Series(mylist) ran but the values in the wrong place. The final thing I got to work was:
df.loc[idx, "B"] = pd.Series(mylist, index=df.index[idx])
My question is, is this the only way of doing this? Feels like there might be a simpler way to achieve the same effect?