首页 文章

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

提问于
浏览
0

我有一个多年来温度值的数据框,我想要做的是将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 回答

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

相关问题