shrey tyagi
shrey tyagi

Reputation: 154

how to run a nested loop in lambda, where one value is coming from dictionary with multiple values for one key?

I wanted to create a new column in dataframe using lambda in python, in which I have to run a loop on dict having multiple values for a key and map it with other variable on which loop is running for each value in dict if 2 values are being assigned to a key.

below is the code I wrote but was not able to map with each dict value but a value pair as whole

acc['metric'] = acc.apply(lambda x: f'{kind}.{squ.units}.{inv}.{self.name}.{x.label}', axis=1)

so here squ is having key value pair in which units key have multiple values at a point.

metric column output is something like -

day.{'cde','abc'}.dev.bde.ops
day.{'test','rmp'}.sand.sab.ops

but i want output to be -

day.cde.dev.bde.ops
day.abc.dev.bde.ops
day.test.sand.sab.ops
day.rmp.sand.sab.ops
    

can someone please suggest how this can be achieved?

Upvotes: 0

Views: 158

Answers (1)

Ynjxsjmh
Ynjxsjmh

Reputation: 30022

You can loop through the value of squ.units, return a list then explode() on column metric.

acc['metric'] = acc.apply(lambda x: [f'{kind}.{unit}.{inv}.{self.name}.{x.label}' for unit in squ.units], axis=1)

acc_ = acc.explode('metric')

Upvotes: 1

Related Questions