Jgallagher
Jgallagher

Reputation: 111

Subset of a dataframe in pandas

I'm trying to create a subset of my 'monthstest' dataframe that only includes results from the year 2018.

enter image description here

When I try the following I get an error,

enter image description here

I have tried changing the data type from an object to a string using the following but it stays as an object.

enter image description here

Any ideas what I should do?

Upvotes: 0

Views: 76

Answers (2)

tommyc
tommyc

Reputation: 61

From your line:

monthstest[monthstest.str.contains('-18')]
# the monthstest inside [] is the entire dataframe, which contains fields other than 'Months', so comparing '-18' against one row of record is not well-defined.

So, you may try to consider the 'Month' column only:

monthstest[monthstest['Month'.str.contains('18-')]]   # i think it is '18-'?

another way to do it (don't know if its more efficient though):

monthstest[ ['18-' in m for m in monthstest['Month']] ]

Upvotes: 0

bglbrt
bglbrt

Reputation: 2098

What you probably want to do is:

monthstest[monthstest["Months"].str.contains("18-")]

Upvotes: 1

Related Questions