running man
running man

Reputation: 1467

Python lambda for loop twice, TypeError: 'generator' object is not callable occur

I have a pandas DataFrame, and I want to combine two elements in column A.

sample:

my_df = pd.DataFrame({'A':[['aa','ab','ac'],['ba','bb','bc','bd']]})
my_df

    A
0   [aa, ab, ac]
1   [ba, bb, bc, bd]

I want this output:

    A                   B
0   [aa, ab, ac]        [[aa, ab], [ab, ac]]
1   [ba, bb, bc, bd]    [[ba, bb], [bb, bc], [bc,bd]]

I am using lambda with for loop twice, but TypeError: 'generator' object is not callable occur. Need help.

my_df['B'] = np.nan
my_df['B'] = my_df['B'].apply(lambda x: [my_df['A'][i][m],my_df['A'][i][m+1]] \
                                                     for i in range(0,len(my_df['A'])) \
                                                     for m in range(0,len(my_df['A'][i])-1))

Upvotes: 0

Views: 464

Answers (1)

akuiper
akuiper

Reputation: 214957

You can do something like this instead:

my_df['B'] = my_df.A.apply(lambda x: list(zip(x[:-1], x[1:])))
my_df

enter image description here


To get list of lists instead of list of tuples:

my_df['B'] = my_df.A.apply(lambda x: list(map(list, zip(x[:-1], x[1:]))))
my_df

enter image description here

Upvotes: 1

Related Questions