Editing specific cells in pandas dataframe?

Viewed 1618

I'm trying to write a function that will enable a user to easily select a specific cell in a pandas dataframe and change its value. For instance, in the dataframe below, I would like to have a user be able to select a cell by date and action, say "2018-03-02" and "Manure", and change the value to "1".

Sample Chart

I have done this already at 2018-03-02 and "Cutting" by using this code (the dataframe is named q):

q.iat[1,1]=1

However, I would like to be able to change the cell using something like q.iat["2018-03-02", "Cutting"]=1, but am not sure how to do this, as it says .iat only recognizes integer postions. Is there something besides .iat I could use, or would I need to set a dictionary for every date and every column?

4 Answers

pd.DataFrame.at

Use at instead of iat for efficient scalar label-based indexing:

q.at['2018-03-02', 'Cutting'] = 1

To summarise:

A short guide to indexing:

  1. Use iat / at for scalar access / setting by integer position or label respectively.
  2. Use iloc / loc for non-scalar access / setting by integer position or label respectively.

Your dataframe is indexed with columns names and index. You can set your index with set_index: df.set_index('date')
Then use both your date index and 'Cutting' column to change a value with .loc: df.loc('2018-03-02','Cutting') = 1

You can select columns by name in pandas simply using its name:

q['Manure']

In order to select the rows you need an index to uniquely identify them, that could be the date if you make sure its in a format that uniquely identifies it. Eg:

q = q.set_index(pd.DatetimeIndex(q['Dates']))

Then you can select each cell doing:

q.loc[<rowIndex>, <colName>]

Related