Reputation: 71
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.'
Upvotes: 1
Views: 1555
Reputation: 862501
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
Upvotes: 2
Reputation: 20669
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]
Upvotes: 3