1

I have a list of columns with the following names (using df.columns.values). I would like to filter out only the columns that contain the value 'EUR'.

How do I do that?

array(['EUR10Y', 'EUR12Y', 'EUR15Y', 'EUR1Y', 'EUR20Y', 'EUR25Y', 'EUR2Y',
       'EUR3Y', 'EUR4Y', 'EUR5Y', 'EUR6Y', 'EUR7Y', 'EUR8Y', 'EUR9Y',
       'GBP10Y', 'GBP12Y', 'GBP15Y', 'GBP1Y', 'GBP20Y', 'GBP25Y', 'GBP2Y',
       'GBP30Y', 'GBP3Y', 'GBP4Y', 'GBP5Y', 'GBP6Y', 'GBP7Y', 'GBP8Y',
       'GBP9Y', 'USD10Y', 'USD15Y', 'USD1Y', 'USD20Y', 'USD2Y', 'USD30Y',
       'USD3Y', 'USD4Y', 'USD5Y', 'USD6Y', 'USD7Y', 'USD8Y', 'USD9Y',
       'EUR10Y', 'EUR12Y', 'EUR15Y', 'EUR1Y', 'EUR20Y', 'EUR25Y', 'EUR2Y',
       'EUR30Y', 'EUR3Y', 'EUR4Y', 'EUR5Y', 'EUR6Y', 'EUR7Y', 'EUR8Y',
       'EUR9Y', 'USD1Y', '00USD10Y', '00USD2Y', '00USD3Y', '00USD5Y',
       '00USD7Y'], dtype=object)

Thanks and kind regards

2
  • cols = [x for x in array if 'EUR' in x] print(df[cols]) Commented Nov 9, 2019 at 22:23
  • 2
    A simple list comprehension should do: [ci for ci in arr if 'EUR' in ci]. If you wnat to filter on the entire dataframe you can use df.filter(like='EUR'). Commented Nov 9, 2019 at 22:27

2 Answers 2

2

If you want to use numpy array,

>>> arr = np.array(
    [
        'EUR10Y', 'EUR12Y', 'EUR15Y', 'EUR1Y', 'EUR20Y', 'EUR25Y', 'EUR2Y',
        'EUR3Y', 'EUR4Y', 'EUR5Y', 'EUR6Y', 'EUR7Y', 'EUR8Y', 'EUR9Y',
        'GBP10Y', 'GBP12Y', 'GBP15Y', 'GBP1Y', 'GBP20Y', 'GBP25Y', 'GBP2Y',
        'GBP30Y', 'GBP3Y', 'GBP4Y', 'GBP5Y', 'GBP6Y', 'GBP7Y', 'GBP8Y',
        'GBP9Y', 'USD10Y', 'USD15Y', 'USD1Y', 'USD20Y', 'USD2Y', 'USD30Y',
        'USD3Y', 'USD4Y', 'USD5Y', 'USD6Y', 'USD7Y', 'USD8Y', 'USD9Y',
        'EUR10Y', 'EUR12Y', 'EUR15Y', 'EUR1Y', 'EUR20Y', 'EUR25Y', 'EUR2Y',
        'EUR30Y', 'EUR3Y', 'EUR4Y', 'EUR5Y', 'EUR6Y', 'EUR7Y', 'EUR8Y',
        'EUR9Y', 'USD1Y', '00USD10Y', '00USD2Y', '00USD3Y', '00USD5Y',
        '00USD7Y'
    ]
)
>>> arr[np.where(np.char.find(arr, 'EUR') >= 0)]
array(['EUR10Y', 'EUR12Y', 'EUR15Y', 'EUR1Y', 'EUR20Y', 'EUR25Y', 'EUR2Y',
       'EUR3Y', 'EUR4Y', 'EUR5Y', 'EUR6Y', 'EUR7Y', 'EUR8Y', 'EUR9Y',
       'EUR10Y', 'EUR12Y', 'EUR15Y', 'EUR1Y', 'EUR20Y', 'EUR25Y', 'EUR2Y',
       'EUR30Y', 'EUR3Y', 'EUR4Y', 'EUR5Y', 'EUR6Y', 'EUR7Y', 'EUR8Y',
       'EUR9Y'], dtype='<U8')

Or filter the column names,

selected = df[[col for col in df.columns if 'EUR' in col]]
Sign up to request clarification or add additional context in comments.

Comments

2

Use pd.DataFrame.filter

df.filter(like='EUR')

Comments

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.