KubiK888
KubiK888

Reputation: 4723

How to assign list value in a pandas df column?

I would like to create a new df column to hold list values.

def add_list_values(row): # row parameter is needed but not in this sample code
    list_val = [1, 'OKOKOK', 2123]
    return list_val

df['new_col'] = df.apply(add_list_values, axis=1)

Error: ValueError: Shape of passed values is (91, 4), indices imply (91, 2)

When I test by simply assigning a column with list value, I got similar error.

df['new_col2'] = [1, 'OKOKOK', 2123]

ValueError: Length of values does not match length of index

Upvotes: 4

Views: 3510

Answers (1)

BENY
BENY

Reputation: 323226

If I understand correctly, try this instead of the line that gives you an error:

df['c']=[[1, 'OKOKOK', 2123]]*len(df)
df
Out[148]: 
   a  b                  c
0  1  1  [1, OKOKOK, 2123]
1  3  4  [1, OKOKOK, 2123]
2  3  4  [1, OKOKOK, 2123]

Upvotes: 6

Related Questions