I have following dataframe :
p p_loc s s0 s0_loc s1 s1_loc s2 s2_loc s3 s3_loc
0 ABCD M AB,AC,AD AB A AC M AD Q NaN U
1 PQRS N PQ,PR,PS,QR PQ B PR N PS R QR V
I'm splitting column s into columns s0,s1,s2,s3 using , as delimeter. I want to pass values from s0,s1,s2,s3,s4,s5,s0_loc,s1_loc,s2_loc,s3_loc to following function which accepts following arguments:
def func(p,p_loc,**args):
print(p)
print(p_loc)
print(kwargs)
I'm passing arguments as follows:
df['new'] = df.apply(lambda x: func(df['p'],df['p_loc'],df['s0'],df['s1'],df['s2'],df['s3'],df['s0_loc'],df['s1_loc'],df['s2_loc'],df['s3_loc']))
I want to know is there any simpler way to pass these arguments(Say, suppose my split of column s results in more than 15-20 columns.. How can I pass these many arguments in a simpler way)...???
Thanks in advance...
Create a set
of positional arguments like:
>>> not_kwargs = {'p', 'p_loc', 's'}
Next filter out kwargs like:
>>> data = df.to_dict()
>>> kwargs = {key:data[key] for key in data.keys() ^ not_kwargs}
If you are using python-2.7 , ^
only operates on set
.
>>> kwargs = {key:data[key] for key in set(data.keys()) ^ not_kwargs}
Call function:
>>> func(data['p'], data['p_loc'], **kwargs)
Not sure if this is what you want, but you can put the columns you require in a seperate list and generate the arguments when you need them.
def func(p, p_loc, *args):
print(p)
print(p_loc)
print(args)
list_of_cols = ['s0', 's1', 's2', 's3', 's0_loc', 's1_loc', 's2_loc','s3_loc']
df['new'] = df.apply(lambda x: func(df['p'], df['p_loc'], *[df[col] for col in list_of_cols]))
Is this what you're looking for?
You can pass a dict into kwargs like this:
d = {
'p': df['p'],
'p_loc': df['p_loc'],
's0': df['s0'],
's1': df['s1'],
...
}
def func(**kwargs):
print(kwargs)
func(**d)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.