简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM