1

Here is the sample code.

import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

df.loc[dl,'A']='Yes'

How do I fill column 'A' with 'No' for column values not in index. Please forgive me if this is a duplicate post.

4 Answers 4

6

np.where

I'm making an assumption that there is a better way to do both 'Yes' and 'No' at the same time. If you truly just want to fill in the 'No' after you've already got the 'Yes' then refer to Fatemehhh's answer

df.loc[:, 'A'] = np.where(df.index.isin(dl), 'Yes', 'No')

Experimental Section

Not meant for actual suggestions

f = dl.__contains__
g = ['No', 'Yes'].__getitem__
df.loc[:, 'A'] = [*map(g, map(f, df.index))]

df

     A
0  Yes
1   No
2  Yes
3  Yes
4  Yes
5   No
6   No
7  Yes
8   No
9   No
Sign up to request clarification or add additional context in comments.

Comments

1

One way is to use the isin function. '~' will reverse it so that the output is elements that are not in dl.

df.loc[~df.index.isin(dl),'A']='No'

Comments

1

First fill all rows of "A" with "No". Then update/overwrite the specific rows with "Yes".

df.loc[:,'A']='No'
df.loc[dl,'A']='Yes'

Comments

1

by using the difference between the list dl and the df list itself:

df.iloc[list( set(df.index) - set(dl))]  = 'No'

or

df.iloc[[x for x in range(len(df)) if x not in dl]] = 'No'

3 Comments

pandas.Index objects already have a difference method. So this should work: df.loc[df.index.difference(dl), 'A'] = 'No'
What's interesting is that loc can handle sets just fine. To shorten up the syntax with a little set literal unpacking (not even sure what to call this) df.loc[{*df.index} - {*dl}, 'A'] = 'No'
Also, for the record, I think this is the most eloquent way of answering OP's actual question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.