Is it possible to input multiple values into a single variable in a Python function?
Question:
Here’s my function:
def function_drop_columns (x,y):
return (x).loc[:,~(x).columns.str.endswith(y)]
x
will always just be one input- specifying a dataframe. For y
, however, there could be many columns I want to drop (which end with different strings). Is there any way to re-write this so y
can be input with multiple values?
I was wondering if I could input some kind ‘or’ operator but it doesn’t seem to have worked.
df1 = function_drop_columns (df,'DATE' or 'STATE')
Do I need to change the function itself or is there way to re-write the input to cover different values?
Answers:
pandas.Series.str.endswith
allows tuple of strings as pattern. Use could use:
function_drop_columns(df, ('DATE', 'STATE'))
You can use *
before an argument to pack value in your function like def function_drop_columns(x, *args):
which pack all value after x like and :
def function_drop_columns(x, *y):
print(x)
print(y)
And with that you get in the console :
>>> function_drop_columns("First value", "Second value", "Third value")
First value
('Second value', 'Third value')
You can also use **
if your want to pass value with keyword like :
def function_drop_columns(x, **y):
print(x)
print(y)
And we get :
>>> function_drop_columns("First value", second="Second value", third="Third value")
First value
{'second': 'Second value', 'third': 'Third value'}
Here’s my function:
def function_drop_columns (x,y):
return (x).loc[:,~(x).columns.str.endswith(y)]
x
will always just be one input- specifying a dataframe. For y
, however, there could be many columns I want to drop (which end with different strings). Is there any way to re-write this so y
can be input with multiple values?
I was wondering if I could input some kind ‘or’ operator but it doesn’t seem to have worked.
df1 = function_drop_columns (df,'DATE' or 'STATE')
Do I need to change the function itself or is there way to re-write the input to cover different values?
pandas.Series.str.endswith
allows tuple of strings as pattern. Use could use:
function_drop_columns(df, ('DATE', 'STATE'))
You can use *
before an argument to pack value in your function like def function_drop_columns(x, *args):
which pack all value after x like and :
def function_drop_columns(x, *y):
print(x)
print(y)
And with that you get in the console :
>>> function_drop_columns("First value", "Second value", "Third value")
First value
('Second value', 'Third value')
You can also use **
if your want to pass value with keyword like :
def function_drop_columns(x, **y):
print(x)
print(y)
And we get :
>>> function_drop_columns("First value", second="Second value", third="Third value")
First value
{'second': 'Second value', 'third': 'Third value'}