1

I tried to add value to a new column for an existing data frame:

val_df["perplexity"][10]=14

There is no column named perplexity and I thought this will create the column. I guessed this answer says the same, but I got the following error:

KeyError: 'perplexity'
Ahmad
  • 7,430
  • 9
  • 60
  • 105

1 Answers1

2

Since 'perplexity' column does not exist yet, a specific index (row) cannot be accessed. So, create the column and assign a default value, then update specific row's value.

val_df["perplexity"] = ''
val_df["perplexity"][10] = 14

EDIT: As suggested by @ALollz below, chained indexing should be avoided to avoid the SettingWithCopy warning. The following code is recommended.

val_df.loc[10, 'perplexity'] = 14
Supratim Haldar
  • 2,196
  • 3
  • 15
  • 25