jarry jafery
jarry jafery

Reputation: 1036

subset the pandas dataframe

I have a pandas dataframe

date            Speed
1986-01-01      0.3
....
2017-03-01      0.4

where date is index of data frame.i want to create a data frame only having data of 1986,2000 and 2017 without date index like

index   date    speed
1       1986    0.3
....
13      2000    0.5

Upvotes: 1

Views: 64

Answers (2)

Amit Wolfenfeld
Amit Wolfenfeld

Reputation: 623

Use the following steps:

# Step one -reindex
df = df.reindex()

# Step two - convert date column to date type
df['date'] = pd.to_datetime(df['date'])

# Step three - create year column using the date object
df['year'] = df.date.dt.year

# Step four - select target years
df[df.year.isin([1986,2000])]

Upvotes: 2

elPastor
elPastor

Reputation: 8956

Assuming your 'date' index is already a datetime dtype:

df.reset_index(inplace = True)
df['date'] = df['date'].dt.year
df = df[df['date'].isin([1986,2000,2017])]

...and if not, add df['date'] = pd.to_datetime(df['date']) after the reset_index

Upvotes: 2

Related Questions