2

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'
3
  • So if you want to add new column called perplexity, you need to specify the values. What are those values? Commented Mar 6, 2019 at 19:20
  • @DanielMesejo they must be set in a loop, however I can set a default value of 0 Commented Mar 6, 2019 at 19:21
  • 1
    Then I guess you are just find doing val_df["perplexity"] = 0 and then setting the other values with the for loop. Commented Mar 6, 2019 at 19:22

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

chained assignment should be avoided. Use .loc: val_df.loc[10, 'perplexity'] = 14
You are right, thanks for pointing it out. I have added this as an edit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.