简体   繁体   English

为什么 lambda 指令返回不同的结果?

[英]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?那么,为什么 lambda 会返回不同的结果呢? And how can I change the lambda code to return the same results as the previous one?以及如何更改 lambda 代码以返回与前一个相同的结果? Thanks in previous感谢之前的

The results are different because lambda function is applied to each row separately.结果不同,因为 lambda 函数分别应用于每一行。 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.因此,例如,在第一行中xAB,CD并且当您for i in x["A"] ,您会遍历每个单独的符号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么此指令不起作用? - Why does this instruction not work? 为什么打印和退货给我不同的结果? - Why are print and return giving me different results? 为什么这两个装饰器返回不同的结果? - Why these two decorators return different results? NLTK每次运行是否返回不同的结果? - Does NLTK return different results on each run? 为什么这两个循环返回不同的结果? - Why do these two loops return different results? 为什么逐位移位会在Python和Java中返回不同的结果? - Why does bit-wise shift left return different results in Python and Java? 为什么sklearn LatentDirichletAllocation的fit和partial_fit会返回不同的结果? - Why does the fit and the partial_fit of the sklearn LatentDirichletAllocation return different results ? 为什么 timeit() 函数在处理函数与字符串表达式时返回不同的结果? - Why does the timeit() function return different results when handed a function vs a string expression? 为什么相同的逻辑方程会在 python 和 c++ 中返回 2 个不同的结果? - Why does the same logical equation return 2 different results in python and c++? 为什么 Python 的 pathlib 和 os lib 为 Windows 中的映射网络驱动器返回不同的结果? - Why does Python's pathlib and os lib return different results for mapped network drives in Windows?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM