1

I want to add a column to a data frame, and also set a list to each element of it, after the execution of below code, nothing changed,

df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})  
df['C'] = 0 
for i in range(len(df)):
    lst = [6,7,8]
    data.iloc[i]['C'] = []
    data.iloc[i]['C'] = lst

Also, based on Assigning a list value to pandas dataframe, I tried df.at[i,'C'] on the above code, and the following error appeared: 'setting an array element with a sequence.'

1
  • Try changing the dtype of column C to object. Commented Jun 11, 2020 at 6:41

2 Answers 2

3

You can use np.tile with np.ndarray.tolist

l = len(df)
df['C'] = np.tile([6,7,8],(l,1)).tolist()
df
   A  B          C
0  1  4  [6, 7, 8]
1  2  5  [6, 7, 8]
2  3  6  [6, 7, 8]
Sign up to request clarification or add additional context in comments.

Comments

2

One idea is use list comprehension:

lst = [6,7,8]

df['C'] = [lst for _ in df.index]

print (df)
   A  B          C
0  1  4  [6, 7, 8]
1  2  5  [6, 7, 8]
2  3  6  [6, 7, 8]

In your solution for me working:

df['C'] = ''
for i in range(len(df)):
    lst = [6,7,8]
    df.iloc[i, df.columns.get_loc('C')] = lst

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.