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

Python 使用str.startswith访问数据帧切片,python,string,pandas,dataframe,startswith,Python,String,Pandas,Dataframe,Startswith,我有一个数据框,其中包含多年的温度值,我想做的是将2015年的所有行放入一个新的数据框中。目前,日期列是一种对象类型,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

我有一个数据框,其中包含多年的温度值,我想做的是将2015年的所有行放入一个新的数据框中。目前,日期列是一种对象类型,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()

注意:如果我这样做

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

我得到了我所期望的,只匹配2015-02-03的日期。str.startswith返回布尔掩码,您无需再次将其与df.Date进行比较。您可以直接使用它编制索引:

weather_2015 = df[df.Date.str.startswith("2015")]
你甚至不需要
.loc
在这里

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

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

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()

该死,这是一个快速的反应。非常感谢你!该死,这是一个快速的反应。非常感谢你!