1

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?

1
  • In my opinion your solution is nice. Commented Dec 1, 2020 at 6:52

2 Answers 2

1

You can use at method, for example

my_list = [np.random.rand(5).tolist() for _ in range(6)]

test_df = pd.DataFrame({'A':np.random.randint(-1,1,6)})
idx = np.where(test_df['A'] < 0)[0]
test_df['B'] = np.random.rand(len(my_list)).astype('object')

for ind in idx:test_df.at[ind,'B'] = my_list[ind]
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not 100% sure but I feel like at should be a last resort. I've +1ed for the answer regardless. Thanks!
0

This way should work fine:

df['B'].loc[idx]=mylist

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.