简体   繁体   中英

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.

在此处输入图像描述

When I try the following I get an error,

在此处输入图像描述

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

在此处输入图像描述

Any ideas what I should do?

What you probably want to do is:

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

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']] ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM