2

I tried to implement a function that automatically does this:

del data['method_code']
del data['aqi']
del data['local_site_name']
del data['cbsa_name']

I have this function:

def del_data_func(data,columns):
  data[columns] =  data[columns].apply(lambda x: del(x))
  return data
del_list = data.columns[['method_code','aqi','local_site_name','cbsa_name']]
del_data_func (data, del_list) 

How can i implement it in the right manner and avoid any errors like this one :

data[columns] =  data[columns].apply(lambda x: del(x))
SyntaxError: invalid syntax

2 Answers 2

3

Why not try this?

data.drop(['method_code', 'aqi', 'local_site_name', 'cbsa_name'], axis=1, inplace=True)

That list could be in fact any list as long as the elements in the list are valid column names from your dataframe.

Sign up to request clarification or add additional context in comments.

Comments

1

I don't know if lambda is requirement, otherwise one way is to loop: If df is:

   col1  col2  col3  col4  col5
0     1     1     1     1     1
1     2     2     2     2     2
2     3     3     3     3     3
3     4     4     4     4     4
4     5     5     5     5     5

Then, function can be written as:

def del_data_func(data,columns):
    for column_name in columns: del data[column_name]

Now, calling the function:

del_list = ['col2', 'col4']
del_data_func (data, del_list) 
print(data)

Output: after col2 and col4 are removed:

   col1  col3  col5
0     1     1     1
1     2     2     2
2     3     3     3
3     4     4     4
4     5     5     5

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.