AAA
AAA

Reputation: 735

how to set value for a specific cell in a dataframe

I have a cell for which i want to its value. I know the cell's column name and its row number (but not its row index)

  A B
h 1 2
n 3 4

Say, i have dataframe above, i have to change the cell on the first row (i dont know its index 'h') with column name 'B'.

I try df['B'].iloc[0]=10, and it works, but it always gives a warning.

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

so what is the correct way to change a cell's value for my case?

Upvotes: 3

Views: 3110

Answers (1)

jpp
jpp

Reputation: 164613

Mixing label and positional indexing requires a little extra work since:

  • loc / at are designed for labels;
  • iloc / iat are designed for positional indexing.

You can convert the row positional index to a label:

df.at[df.index[0], 'B'] = 10

Or you can convert the column label to a positional index:

df.iat[0, df.columns.get_loc('B')] = 10

Note: at / iat should be preferred to loc / iloc for fast scalar access / setting.

Upvotes: 1

Related Questions