Pandas Lambda函数将长度函数应用于数据帧会产生不同的输出
我有一个数据框: 我想计算行index=4中每个单元格的长度。 我执行了两个命令,两个命令给出了不同的答案。有人能解释一下这里发生了什么吗Pandas Lambda函数将长度函数应用于数据帧会产生不同的输出,pandas,lambda,string-length,Pandas,Lambda,String Length,我有一个数据框: 我想计算行index=4中每个单元格的长度。 我执行了两个命令,两个命令给出了不同的答案。有人能解释一下这里发生了什么吗 a b c d e f g 0 1 2 3 4 5 6 first 1 3 4 5 6 7 8 second 2 6 7 8 9 10 11 third 3 first second third fourth fifth six
a b c d e f g
0 1 2 3 4 5 6 first
1 3 4 5 6 7 8 second
2 6 7 8 9 10 11 third
3 first second third fourth fifth sixth fourth
4 column column column column column column fifth
First Command:
**df2.loc[4].apply(lambda x: len(x))**
Output:
a 6
b 6
c 6
d 6
e 6
f 6
g 5
Name: 4, dtype: int64
Second Command:
**df2.loc[4:].apply(lambda x: len(x))**
Output:
a 1
b 1
c 1
d 1
e 1
f 1
g 1
dtype: int64
- Python新手
df2.loc[4]
生成一个系列(包含7个元素),而调用df2.loc[4://code>(4:
是一个切片)生成一个数据帧(包含1行7列)。尝试对这两种方法使用print()
和type()
,以查看差异
- 在一个系列中,
apply
对该系列的值调用函数,因此您确实获得了所需的字符串值的长度
- 在数据帧上,
apply
对每列调用您的函数,计算列中的元素(行)数,它是1,因为[4://code>切片定义了一行(尝试[2:5]
,您将得到3而不是1)
顺便说一句,您的lambda函数与len
函数相同,因此您只需编写。apply(len)
欢迎使用堆栈溢出!请以我们可以使用的方式发布您的数据帧,请参阅此帮助。@joao:谢谢。我现在格式化了。看起来好多了我想谢谢你的帮助现在我明白了。如果我想迭代地检查数据帧中每个单元格的长度,还有一件事。那么@joaodf2.applymap(len)