3

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)

Dervin Thunk
  • 17,583
  • 26
  • 110
  • 202
  • possible duplicate of [Set value for particular cell in pandas DataFrame](http://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe) – LondonRob Aug 06 '15 at 16:27

1 Answers1

3

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.

iayork
  • 5,196
  • 6
  • 39
  • 42
  • It still gives me the same warning using your method. Is there a way I'm not really working with cells/a dataframe? – Dervin Thunk Aug 04 '15 at 19:10
  • What happens if you make your data frame with "df = pd.DataFrame({'animal':('tiger',), 'id':(1,)})" and then use "df.loc[0, 'id'] = 'Lion'" ? – iayork Aug 04 '15 at 19:15
  • to create my (what I think is) a dataframe, I do `df=pd.read_csv("some/file.csv")`... does that return a dataframe? (Thanks for your patience) – Dervin Thunk Aug 04 '15 at 19:27
  • Try check: `checkcontains_latlong.is_copy`. Is it True or False? – jezrael Aug 04 '15 at 19:32
  • It creates a dataframe, but it is not certain that its structure (its index names and indices, its column names and order) will match the patterns used here. What do you see with df.head()? (You may want to edit your question to show it there.) – iayork Aug 04 '15 at 19:32
  • If it is `False`, you can turn off it - `contains_latlong.is_copy = False` – jezrael Aug 04 '15 at 19:33