3

I have the df with following columns:

df.columns

['total_rech_num_6', 'total_rech_num_7', 'total_rech_num_8','max_rech_amt_6', 'max_rech_amt_7', 'max_rech_amt_8','max_amt_6', 'max_amt_7', 'max_amt_8'].

I would like to select only those columns which has 'rech' AND '6' in the column name.

I tried this to select columns with'rech':

recharge_cols = [col for col in df.columns if 'rech' in col]

But i dont kow how to add the other string condition to get the 'rech' AND '6' columns. Need help!!

0

3 Answers 3

4

You can use this 1 line expression:

   recharge_cols = [i for i in list(df) if 'rech' in i and '6' in i]
Sign up to request clarification or add additional context in comments.

Comments

1

Use and with another in statement:

recharge_cols = [col for col in df.columns if 'rech' in col and '6' in col]
print (recharge_cols)
['total_rech_num_6', 'max_rech_amt_6']

Pandas solution:

recharge_cols = df.columns[df.columns.str.contains('rech') & 
                           df.columns.str.contains('6')].tolist()

print (recharge_cols)
['total_rech_num_6', 'max_rech_amt_6']

Comments

0

Try this:

recharge_cols = [col for col in df.columns if 'rech' in col and '6' in col]

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.