Crysers
Crysers

Reputation: 535

Pandas DataFrame: Add a list to each cell by iterating over df with new column does not work

DataFrame with some columns a and b.
I now want to add a new column c that should contain lists (of different lengths).

df1 = pd.DataFrame({'a':[1,2,3], 'b':[5,6,7]})
new_col_init = [list() for i in range(len(df1)]
df1['c'] = pd.Series(new_col_init,dtype='object')
print(df1)

gives:

   a  b   c
0  1  5  []
1  2  6  []
2  3  7  []

Why Am I unable to do the following:

for i in range(len(df1)):
    df1.loc[i,'c'] = [2]*i

This results in ValueError: cannot set using a multi-index selection indexer with a different length than the value.

However this works:

df1['c'] = pd.Series([[2], [2,2], [2,2,2]])
print(df1)

Result:

    a   b   c
0   1   5   [2]
1   2   6   [2, 2]
2   3   7   [2, 2, 2]

Is there a way to assign the lists by iterating with a for-loop? (I have a lot of other stuff that gets already assigned within that loop and I now need to add the new lists)

Upvotes: 0

Views: 474

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195468

You can use .at:

for i, idx in enumerate(df1.index, 1):
    df1.at[idx, "c"] = [2] * i

print(df1)

Prints:

   a  b          c
0  1  5        [2]
1  2  6     [2, 2]
2  3  7  [2, 2, 2]

Upvotes: 3

mujjiga
mujjiga

Reputation: 16886

df1.loc[:, 'c'] = [[2]*(i+1) for i in range(len(df1))]

Upvotes: 0

sushanth
sushanth

Reputation: 8302

Here is a solution you can try out using Index.map,

df1['c'] = df1.index.map(lambda x: (x + 1) * [2])

   a  b          c
0  1  5        [2]
1  2  6     [2, 2]
2  3  7  [2, 2, 2]

Upvotes: 0

Related Questions