Martin J
Martin J

Reputation: 2159

Replace a list value with another array in pandas

I am tring to replace a list value with another list value in a pandas but it raises an error : cannot set using a multi-index selection indexer with a different length than the value. Is it wrong practice to work with list values in pandas? Thank you

import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [[123, 123123],[123, 123123],[123, 123123],[123, 123123]]
        }
df = pd.DataFrame(cars, columns = ['Brand', 'Price'])
df[1, 'Price'] = [2342, 23423]

print(df)

Upvotes: 0

Views: 197

Answers (2)

SunilG
SunilG

Reputation: 345

You better create two columns of out your Price column like this. But if you still have a good reason to have a list in the Price column and want to update it, use below code:

df.iloc[1, 1] = [2342, 23423]

This is integer-location based indexing for selection. 'Price' is in the index=1 position column wise.So, the 2nd 1 refers to 'Price' column and the 1st 1 refers to the actual row index.

Upvotes: 0

jezrael
jezrael

Reputation: 863531

Use DataFrame.loc:

df.loc[1, 'Price'] = [2342, 23423]

print(df)
0     Honda Civic  [123, 123123]
1  Toyota Corolla  [2342, 23423]
2      Ford Focus  [123, 123123]
3         Audi A4  [123, 123123]

Is it wrong practice to work with list values in pandas?

I think working with lists in pandas is not good idea, if possible create 2 columns here.

Upvotes: 1

Related Questions