简体   繁体   中英

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))

You can do something like this instead:

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

在此处输入图片说明


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

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM