1

I am setting a column based on a list of indices, which I computed earlier. I also deleted some indices during computations, so some indices are no longer part of my dataframe. This simplified example shows what's happening now:

df = pd.DataFrame(data=[[1 , 2, False], [4 , 5, False]], columns=["col1", "col2", "col3"], index=[1, 3])

df.loc[[1, 2], 'col3'] = True

Obviously I am getting an KeyError:

KeyError: '[2] not in index'

Unfortunately .loc() does not provide something like error="ignore". Would be iterating over the list catching the KeyError with a try-catch-block the only solution or is there a nicer way to do that?

Any hints? Thanks

0

2 Answers 2

2

You can use .index.intersection() to select only "good keys":

good_keys = df.index.intersection([1, 2])
df.loc[good_keys, "col3"] = True

print(df)

Prints:

   col1  col2   col3
1     1     2   True
3     4     5  False
Sign up to request clarification or add additional context in comments.

Comments

1

reindex

Places null rows or columns where index values didn't exist before.

df = df.reindex([1, 2, 3])
df.loc[[1, 2], 'col3'] = True

df

   col1  col2   col3
1   1.0   2.0   True
2   NaN   NaN   True
3   4.0   5.0  False

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.