0

I have a Pandas Dataframe: I wanted to calculate the length of each cell in row index=4. I executed 2 commands and both give different answers. Can somebody explain what is happening here

    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

  • New to Python
Shayantu
  • 3
  • 3
  • 1
    Welcome to Stack Overflow! Please post your dataframe in a way that we can use it, see this [page](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) for help. – joao May 23 '21 at 10:05
  • @joao: Thanks. I formatted it now. Looks better I think – Shayantu May 23 '21 at 10:11

1 Answers1

0

The reason for that difference is that calling df2.loc[4] produces a Series (with 7 elements), whereas calling df2.loc[4:] (4: is a slice) produces a DataFrame (with 1 row and 7 columns). Try using print() and type() on the two to see the difference.

  • on a Series, apply invokes your function on the values of the Series, so you are indeed getting the lengths of the string values like you wanted.

  • on a DataFrame, apply is invoking your function on each column, counting the number of elements (rows) in the column, and it's 1 because the [4:]slice defines a single row (try [2:5], you'll get 3 instead of 1).

BTW, your lambda function is identical to the len function, so you can just write .apply(len).

joao
  • 2,220
  • 2
  • 11
  • 15
  • Thanks for the help It was clear to me now. Just 1 more thing, if I want to check the length of each cell of a dataframe iteratively. Then what is the solution @joao – Shayantu May 23 '21 at 11:53
  • `df2.applymap(len)` – joao May 23 '21 at 13:08