JamesHudson81
JamesHudson81

Reputation: 2273

Apply a condition to an index based on the values in a list

I have a df:

              A   B   C

    'F'      2    4   ss1
    'G'      3    4   ss1

Then I have a list1:

['ss1','ss4']

I would like that if any element of the list1 exists in column C of the df, then apply a space to the beginning of the index name to obtain this output:

              A   B   C

    ' F'      2    4   ss1
    ' G'      3    4   ss1

Upvotes: 1

Views: 17

Answers (1)

jezrael
jezrael

Reputation: 863226

Use numpy.where or Index.where and condition with Index.isin:

df.index = np.where(df['C'].isin(list1), ' ' + df.index, df.index)

Or:

df.index = df.index.where(~df['C'].isin(list1), ' ' + df.index)

Upvotes: 2

Related Questions