0

this is my dataframe:

df = pd.DataFrame({'sym': ['msft', 'amd', 'bac', 'tsla'], 'close': [100, 30, 70, 80], 'sector': ['tech', 'tech', 'bank', 'auto'], 'watch_list': [1, 2, 2, 1]})

and this is the simpilified form of function that I want to use:

def add_volume(df):
  df['volume'] = [1000, 2000, 3000, 4000]
  return df

I want to pass two optional arguments(sector, watch_list) to my function that select the rows that I want for example if I call the function like this

add_volume (df, sector=['tech'], watch_list=[1])

It returns the first row.

And if I just call it like this

add_volume(df, watch_list = [1])

it returns the first and last row. I want both of the arguments to be optional.

1
  • 1
    def add_volume(df, sector=None, watch_list=None): Inside function check if arguments are not None and use them or not. Commented Jul 6, 2019 at 21:24

1 Answer 1

3

You can use *args parameter. This allows you to add any number of parameters(optional parameters) after first parameter(in your case), which is compulsory.

Try this:

import pandas as pd
df = pd.DataFrame({'sym': ['msft', 'amd', 'bac', 'tsla'], 'close': [100, 30, 70, 80], 'sector': ['tech', 'tech', 'bank', 'auto'], 'watch_list': [1, 2, 2, 1]})

def add_volume(df, *args, **kwargs):
    sector = kwargs.get('sector', None)
    watch_list = kwargs.get('watch_list', None)

    df['volume'] = [1000, 2000, 3000, 4000]
    if sector and watch_list:
        return df[(df['sector']==sector) & (df['watch_list']==watch_list)]
    elif sector:
        return df[df['sector']==sector]
    elif watch_list:
        return df[df['watch_list']==watch_list]
    else:
        return df

print(add_volume(df, sector='tech', watch_list=1)) 
print(add_volume(df, watch_list=1)) 
print(add_volume(df, sector='tech'))
print(add_volume(df))

output:

   close sector   sym  watch_list  volume
0    100   tech  msft           1    1000

   close sector   sym  watch_list  volume
0    100   tech  msft           1    1000
3     80   auto  tsla           1    4000

   close sector   sym  watch_list  volume
0    100   tech  msft           1    1000
1     30   tech   amd           2    2000

   close sector   sym  watch_list  volume
0    100   tech  msft           1    1000
1     30   tech   amd           2    2000
2     70   bank   bac           2    3000
3     80   auto  tsla           1    4000
Sign up to request clarification or add additional context in comments.

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.