【问题标题】:Filtering and manipulating datetime in pandas dataframe在熊猫数据框中过滤和操作日期时间
【发布时间】:2020-04-06 08:36:25
【问题描述】:

好的,伙计们,我想知道发生了什么。我有一个熊猫 dataframe,我从 MySQL 拉出来的。

其实这是我的查询语法:

query = "SELECT * FROM mywebsite.com WHERE date BETWEEN '2019-12-01' AND '2020-03-31'"

websitedata = pd.read_sql(query,con=engine)

然后我将exported 的数据设为CSV。现在今天reading 来自CSV 并尝试将数据拆分到chunksdates

Dec2019 = df.loc[(df.date >= "2019-12-01") & (df.date <= "2019-12-31")]
Jan2020 = df.loc[(df.date >= "2020-01-01") & (df.date <= "2020-01-31")]
Feb2020 = df.loc[(df.date >= "2020-02-01") & (df.date <= "2020-02-29")]
Mar2020 = df.loc[(df.date >= "2020-03-01") & (df.date <= "2020-03-31")]


len(df) == len(Dec2019) + len(Jan2020) + len(Feb2020) + len(Mar2020) # gives me False

事实上len(Dec2019) + len(Jan2020) + len(Feb2020) + len(Mar2020)376440

len(df) 给出384274

如何预览帧以查看问题所在?喜欢 2019 年 12 月、2020 年 1 月、...、2020 年 3 月等了解问题?

PS:日期已经是pandas datetime

【问题讨论】:

  • 我诊断可能丢失数据点的一种方法是将“年月”列插入 df a) 通过 strptime 将字符串解析为实际日期时间 b) 然后创建一个结合列df.date.year + '-' df.date.month c) 在新的年月列上绘制一个 value_counts
  • date 是日期时间还是实际字符串? df['date'].dtype 显示什么?
  • Others = df.loc[(df.date &lt; "2019-12-01") | (df.date &gt; "2020-03-31")]。是空的吗?
  • 如果日期已经是日期时间,请尝试:df['date'].to_period('M').value_counts()...
  • @JonClements 我得到AttributeError: 'RangeIndex' object has no attribute 'to_period' 它没有设置为索引,而是设置为单独的列

标签: python pandas dataframe datetime pandasql


【解决方案1】:

所以我想出了最有效的方法来做到这一点,它给了我准确的框架,没有日期泄漏。

使用datetime dt accessor

Jan2020 = df[df.date.dt.month == 1]
Dec2019 = df[df.date.dt.month == 12]
Feb2020 = df[df.date.dt.month == 2]
Mar2020 = df[df.date.dt.month == 3]

事实上这现在返回True

len(df) == len(Dec2019) + len(Jan2020) + len(Feb2020) + len(Mar2020)

信用:How to filter a dataframe of dates by a particular month/day?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    相关资源
    最近更新 更多