使用str.startswith访问数据帧切片

时间:2017-08-28 00:30:50

标签: python string pandas dataframe startswith

我有一个多年来温度值的数据框,我想要做的是将2015年的所有行放入新的数据框中。目前,Date列是一种对象类型,其str格式如下所示:YYYY-MM-DD

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv("C:\\whatever\weather.csv")

weather_2015 = df.loc[df.Date == df.Date.str.startswith("2015"), :]
weather_2015.head()

this is what the data looks like in the main data frame

注意:如果我做了类似

的事情
weather_2015 = df.loc[df.Date == "2015-02-03", :]
weather_2015.head()

我得到了我所期待的,仅与2015-02-03匹配的日期

1 个答案:

答案 0 :(得分:2)

pd.Series.str.startswith返回一个布尔掩码,您无需再次将其与df.Date进行比较。您可以直接使用它进行索引:

weather_2015 = df[df.Date.str.startswith("2015")]

这里甚至不需要.loc

请注意,如果您想对此切片进行更改,您可能更喜欢副本,在这种情况下,您应该致电df.copy

weather_2015 = df[df.Date.str.startswith("2015")].copy()