简体   繁体   中英

Why does the lambda instruction return different results?

import pandas as pd

df = pd.DataFrame([['AB,CD'],['AB,FJS'],['DG']],
                   index = [1,2,3],columns=['A'])

Why do the following two codes return different results

for i in df["A"]:
    for n in i.split(","):
        print(n)

which returns

AB
CD
AB
FJS
DG

but the other code

def fx(x):
    for i in x["A"]:
        for n in i.split(","):
            print(n)
df.apply(lambda x: fx(x), axis = 1)

returns

A
B
,
C
D
A
B
,
F
J
S
D
G

So, why does lambda return different results? And how can I change the lambda code to return the same results as the previous one? Thanks in previous

The results are different because lambda function is applied to each row separately. So, for example, in the first row x is AB,CD and when you write for i in x["A"] , you iterate over each separate symbol.

def fx(x):
    for i in x["A"].split(","):
        print(i)
df.apply(lambda x: fx(x), axis = 1)

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