tiru
tiru

Reputation: 363

how can i remove entire row if a column has more than 10 characters using pandas

Delete entire record if column is more than 10 characters how can i delete that entire record.

My dataframe is

Sl.no     name                 reason
1         sara                 hello 
2          ram                  how are you?
3          raghu                how do you do?
4          sai                   hey !!

Expected Output:

Sl.no     name                 reason
1         sara                 hello 
2          sai                 hey !!

Thanks inadvance.

Upvotes: 3

Views: 2406

Answers (2)

jpp
jpp

Reputation: 164643

Boolean indexing with a list comprehension is efficient:

df = df[[len(i) <= 10 for i in df['reason']]]

But there are a few other approaches:

df = pd.concat([df]*2000)

%timeit df['reason'].map(len).le(10)          # 2.32 ms per loop
%timeit df['reason'].str.len().le(10)         # 2.6 ms per loop
%timeit [len(i) <= 10 for i in df['reason']]  # 1.18 ms per loop

Upvotes: 1

jezrael
jezrael

Reputation: 862591

I believe need boolean indexing with inverted mask from > to <= and find lengths by Series.str.len:

df = df[df['reason'].str.len() <= 10]
print (df)
   Sl.no  name  reason
0      1  sara   hello
3      4   sai  hey !!

Upvotes: 5

Related Questions