2017-08-28 36 views
0

我有一個多年來具有溫度值的數據幀,我想要做的是將2015年的所有行放入新的數據幀中。目前,日柱是與海峽格式看起來像這樣的對象類型:YYYY-MM-DD使用str.startswith訪問數據幀切片

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

回答

2

pd.Series.str.startswith返回布爾掩碼,您不需要將其與df.Date進行比較a獲得。你可以只指數隨它直接:

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

你甚至都不需要.loc這裏。

請注意,如果你想在這片變化,你可能更喜歡一個副本,在這種情況下,你應該叫df.copy

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

蕩,這是一個快速反應。非常感謝你! – CaseyK