pang2016
pang2016

Reputation: 539

apply a function to dataframe

I'm new to using apply:

import pandas
df=pandas.DataFrame({"k1":['2017-03-07','2017-02-07','2017-01-15'],
                 "k2":[1,2,3],})

I want to get the data that matches some month. For example: I want to get the month == 2:

df[pandas.to_datetime(df.k1).dt.month == 2]

But I want to write a function with a parameter can match the month. this is my function. It doesn't work.

def get_month(df, mon=1):
    return df[pandas.to_datetime(df.k1).dt.month == mon]

df.apply(get_month)

Upvotes: 1

Views: 69

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49812

You need to restructure your code a bit. apply works per row.

Code:

def get_month(mon):
    return lambda x: pandas.to_datetime(x.k1).month == mon

Test Code:

df = pandas.DataFrame({"k1": ['2017-03-07', '2017-02-07', '2017-01-15'],
                       "k2": [1, 2, 3], })

print(df[df.apply(get_month(1), axis=1)])

Results:

           k1  k2
2  2017-01-15   3

Upvotes: 1

Related Questions