Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace the content of an entire Pandas' cell with a string?

Tags:

python

pandas

I have a dataframe with a row that contains the following:

id    animal
1     tiger

I would like to simply "set" the value of 1 to, say, "lion".

contains_latlong.iloc[1]["animal"]="lion"

is something that Pandas doesn't like. Being new, I'm getting mixed up with copying vs modifying dataframes, I suppose. The warning is

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

What is the way to set a given value of a cell? (And, in general, how should I think about this?)

Edit: str.replace is not what I'm looking for here. I just want to replace the content of that cell (whatever it is, rather than a regex), with some other string (literal)

like image 704
Dervin Thunk Avatar asked Dec 10 '25 10:12

Dervin Thunk


1 Answers

In general the approach is to use index and column identifiers:

df.loc[1, 'id'] = 'Lion'

yields

  animal    id
1  tiger  Lion

without any warnings.

Your example uses "iloc" rather than "loc", which means you need to access both columns and index by index, not name. Something like df.iloc[0, 0] = 'Lion' might work in your example, assuming that you're showing a complete row without the index.

like image 106
iayork Avatar answered Dec 12 '25 22:12

iayork



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!