Mike
Mike

Reputation: 4259

Select date subsets in Pandas Columns

I have a pandas DataFrame with datetime.time on the index and datetime.date on the columns. E.g.

df =

          2006-02-01  2006-02-02     ...      2006-05-29  2009-06-01
08:00:00     1.45685     1.43830     ...         1.41020     1.42045
08:00:01     1.45685     1.43825     ...         1.41030     1.42040
08:00:02     1.45685     1.43810     ...         1.41025     1.42050
08:00:03     1.45685     1.43825     ...         1.41025     1.42060
...

I would like to select only columns from 2006. How do I do this easiest and fastest?

I found df.T['2006'].T does the trick, but it in involves two transposes. Can't this be done directly on the columns?

Upvotes: 1

Views: 182

Answers (2)

Yonatan Zax
Yonatan Zax

Reputation: 39

try this code:

def getSubsetColumnsByYear(dataframe, year):
    df = dataframe
    try:
        startAt = df.columns.get_loc(year + '-01-01')
        endAt = df.columns.get_loc(year + '-12-31')

        return df[df.columns[startAt:endAt+1]]
    except KeyError:
        print('Not a valid year')


def testMethod():
    import pandas as pd
    data = { '2016-01-01':[1,1,1], '2016-01-02':[2,2,2], '2016-01-03':[3,3,3], '2016-01-04':[4,4,4], '2016-12-31':[31,31,31], '2017-01-01':[2,2,2],}
    df = pd.DataFrame(data=data)

    newdf = getSubsetColumnsByYear(df, '2016')
    print(newdf)

testMethod()

Upvotes: 1

Mitchell Posluns
Mitchell Posluns

Reputation: 86

if your columns are datetime.date objects, try:

df.loc[:, '2006-01-01':'2006-12-31']

Upvotes: 1

Related Questions