2

I want to edit a row in in my dataframe such as:

index columnA ColumnB
0     1       [a, b]
1     3       [c, b]
2     4       [a, b]
3     6       [d, a, b]

Lets say I want to replace the [c, b] with [q, y] where the columnA is value 3. How would I go about doing that. I tried the following:

df.at[df['columnA'] == 3, 'ColumnB'] = [q, y]

Both are columns and I would like to edit the row based on the columnA value and not the index.

Bada
  • 100
  • 11
  • Please take the time to read [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as the guide on [how to provide a minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve) and update your question accordingly. – elemakil Mar 03 '19 at 15:42
  • Possible duplicate of [Python pandas insert list into a cell](https://stackoverflow.com/questions/26483254/python-pandas-insert-list-into-a-cell) – yatu Mar 03 '19 at 15:50
  • It is sadly not a duplicate. Since I do not want to search by index but by column condition – Bada Mar 03 '19 at 19:13
  • @elemakil Is the question correct now? – Bada Mar 03 '19 at 19:14

2 Answers2

2

You can try this one. Let me know if it works

df.loc[(df['columnA'] == 3),'columnB']= '[p, q]'

Dataframe is created using

df = pd.DataFrame({'columnA': [1, 3, 4, 6],'columnB': [['a','b'],['c','b'],['a','b'],['a','b']]})
Devarshi Mandal
  • 703
  • 8
  • 16
1

Dataframes are generally referenced as follows. Assuming your dataframe is called df

df.loc[row_name, column_name] = val

Alternatively,

df.iloc[row_index, column_index] = val

.loc uses the explicit column/row names and .iloc uses the numerical index (just like numpy or a list).

So, in your example assuming that you haven't changed the index from the default and assuming that both columns are in fact data columns and not the index

df.loc[2, 'ColumnB'] = [q,y]

or, equivelantly

df.iloc[2, 1] = [q,y]

However, with Dataframes, the index is just as important as the columns when it comes to referencing values. From your question, it isnt clear what you've used as the index and what your actual data columns are.

Edit:

The ValueError can be overcome by using Dataframe.at i.e. try

df.at[2, 'ColumnB'] = [q,y]

P.Sauerborn
  • 69
  • 1
  • 3
  • 2
    When trying your loc solution, I get the following error: ValueError: Must have equal len keys and value when setting with an iterable – Bada Mar 03 '19 at 17:10