Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

python - using len() in Pandas dataframe

This is the look of my DataFrame:

   StateAb    GivenNm    Surname                  PartyNm PartyAb  ElectedOrder
35      WA        Joe    BULLOCK   Australian Labor Party     ALP             2
36      WA  Michaelia       CASH                  Liberal      LP             3
37      WA      Linda   REYNOLDS                  Liberal      LP             4
38      WA      Wayne  DROPULICH  Australian Sports Party    SPRT             5
39      WA      Scott     LUDLAM          The Greens (WA)     GRN             6

and I want to list a list of senators whose surname is more than 9 characters long.

So I think the code should be like this:

df[len(df.Surname) > 9]

but this raises a KeyError, where did I go wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The correct way to filter a DataFrame based on the length of strings in a column is

df[df['Surname'].str.len() > 9]

df['Surname'].str.len() creates a Series of lengths for the surname column and df[df['Surname'].str.len() > 9] filters out the ones less than or equal to 9. What you did is to check the length of the Series itself (how many rows it has).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...