【问题标题】:How to Box Plot Panda Timestamp series ? (Errors with Timestamp type)如何对 Pandas 时间戳系列进行箱线图绘制? (时间戳类型的错误)
【发布时间】:2019-03-15 17:59:06
【问题描述】:

我正在使用:

熊猫版本 0.23.0

Python 3.6.5 版

Seaborn 版本 0.81.1

我想要一列时间戳数据的箱线图。我的数据框不是时间序列,索引只是一个整数,但我使用以下方法创建了一列时间戳数据:

# create a new column of time stamps corresponding to EVENT_DTM
data['EVENT_DTM_TS'] =pd.to_datetime(data.EVENT_DTM, errors='coerce')

我过滤掉所有由强制产生的 NaT 值。

dt_filtered_time = data[~data.EVENT_DTM_TS.isnull()]

此时我的数据看起来不错,我可以确认 EVENT_DM_TS 列的类型是 Timestamp,没有无效值。

最后生成我调用的单变量箱线图:

ax = sns.boxplot(x=dt_filtered_time.EVENT_DTM_TS)

并得到错误:

TypeError: ufunc add 不能使用类型为 dtype('M8[ns]') 和 dtype('M8[ns]') 的操作数

我已经谷歌搜索并找到:

https://github.com/pandas-dev/pandas/issues/13844 https://github.com/matplotlib/matplotlib/issues/9610

这似乎表明数据类型表示存在问题。

我还看到了对 pandas 0.21.0 版问题的引用。

任何人都有一个简单的修复建议,或者我是否需要使用不同的数据类型来绘制箱线图。我想获取时间戳数据分布的单张图片。

【问题讨论】:

  • 您应该始终能够使用数字进行绘图。 IE。将时间戳转换为浮点数(例如秒),并相应地勾选坐标轴。

标签: pandas matplotlib timestamp seaborn boxplot


【解决方案1】:

这是我最终得到的代码:

import time
@plt.FuncFormatter
def convert_to_date_string(x,pos):
    return time.strftime('%Y-%m',time.localtime(x))


plt.figure(figsize=(15,4))
sns.set(style='whitegrid')
temp = dt_filtered_time.EVENT_DTM_TS.astype(np.int64)/1E9
ax = sns.boxplot(x=temp)
ax.xaxis.set_major_formatter(convert_to_date_string)

结果如下:

归功于 ImportanceOfBeingErnest,他的comment 向我指出了这个解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2015-03-07
    • 1970-01-01
    相关资源
    最近更新 更多