Drop few rows of a pandas dataframe using lambda

Viewed 8722

I'm currently facing a problem with method chaining in manipulating data frames in pandas, here is the structure of my data:

import pandas as pd

lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
df = pd.DataFrame(
    {'Frenquency': lst1,
     'lst2Tite': lst2,
     'lst3Tite': lst3
    })

the question is get entries(rows) if the frequency is less than 6, but it needs to be done in method chaining.

I know using a traditional way is easy, I could just do

df[df["Frenquency"]<6]

to get the answer.

However, the question is about how to do it with method chaining, I tried something like

df.drop(lambda x:x.index if x["Frequency"] <6 else null)

but it raised an error "[<function <lambda> at 0x7faf529d3510>] not contained in axis"

Could anyone share some light on this issue?

5 Answers

This is an old question but I will answer since there is no accepted answer for future reference.

df[df.apply(lambda x: True if (x.Frenquency) <6 else False,axis=1)]

explanation: This lambda function checks the frequency and if yes it assigns True otherwise False and that series of True and False used by df to index the true values only. Note the column name Frenquency is a typo but I kept as it is since the question was like so.

Feel this post did not have the answers that addressed the spirit of the question. The most chain-friendly way is (probably) to use Panda's .loc.

import pandas as pd

lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
df = pd.DataFrame({"Frequency": lst1, "lst2Tite": lst2, "lst3Tite": lst3})

df.loc[lambda _df: 6 < _df["Frequency"]]

Simple!

Related