在Pandas中使用DateTimeIndex打印时遇到空数据帧错误

2024-05-12 17:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Pandas绘制时间序列来绘制积分图,但我收到错误TypeError: Empty 'DataFrame': no numeric data to plot。直接使用matplotlib可以工作,但是我认为我误用了这个库,我想确保我在使用Pandas时不会走错路。在

以下是正在发生的事情:

我有一个包含两列的数据文件。第一列是时间戳,第二列是已用时间。两者都以纳秒为单位。我用以下方法读取数据:

data = pd.read_table('trace.log', sep=" ", header=None,
    names=("start", "latency"))
print(data.head())
print(data.dtypes)

包含以下数据:

^{pr2}$

然后我将start转换为datetime64[ns],并将其作为索引,并将latency转换为timedelta64[ns]。在

data.start = pd.to_datetime(data.start, unit="ns")
data.latency = pd.to_timedelta(data.latency, unit="ns")
data.set_index('start', inplace=True)

print(data.head())
print(data.dtypes)
print(data.index)

所以现在我有了一个时间序列,它有一个日期时间索引和一个时间增量表示的延迟:

                                      latency
start                                        
1970-01-01 07:41:08.827345634 00:00:00.754210
1970-01-01 07:41:08.827495897 00:00:01.395999
1970-01-01 07:41:08.827574509 00:00:01.395592
1970-01-01 07:41:08.827605687 00:00:01.381083
1970-01-01 07:41:08.827634020 00:00:01.381130
latency    timedelta64[ns]
dtype: object
DatetimeIndex(['1970-01-01 07:41:08.827345634',
               '1970-01-01 07:41:08.827495897',
               ...
               '1970-01-01 08:11:07.739615123',
               '1970-01-01 08:11:07.756520620'],
              dtype='datetime64[ns]', name='start', length=437915, freq=None)

我看到的问题是当我试图描绘这个。根据我看到的示例,我应该能够运行:

data.latency.plot()

生成延迟与启动时间的关系图,但我得到以下错误:

/opt/conda/lib/python3.5/site-packages/pandas/tools/plotting.py in _compute_plot_data(self)
   1092         if is_empty:
   1093             raise TypeError('Empty {0!r}: no numeric data to '
-> 1094                             'plot'.format(numeric_data.__class__.__name__))
   1095 
   1096         self.data = numeric_data

TypeError: Empty 'DataFrame': no numeric data to plot

请注意,如果我使用plt.plot(data.index, data.latency)绘制数据,那么我就得到了我期望的结果。我想我一定是错过了一个重要的理解,或者我看到了一个bug。能够使用熊猫绘制整合图将是一件好事。在


Tags: tonodataindexplot时间绘制start
1条回答
网友
1楼 · 发布于 2024-05-12 17:04:01

您可以使用set_major_formatter()自定义时间刻度:

import io
import datetime
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd

data = """\
            start    latency
0  27668827345634  754210039
1  27668827918895  753710503
2  27668827809194  754495193
3  27668827974232  754464123
4  27669581667404   60338395
"""
data = pd.read_csv(io.StringIO(data), sep='\s+', index_col=0)

data.start = pd.to_datetime(data.start, unit="ns")
# convert nanoseconds to seconds
data.latency /= 10**9

# define custom Ticker formatter function
def timeTicks(x, pos):
    return str(datetime.timedelta(seconds=x))

formatter = matplotlib.ticker.FuncFormatter(timeTicks)

ax = data.plot(x='start', y='latency')

# format yticks
ax.yaxis.set_major_formatter(formatter)

plt.show()

enter image description here

相关问题 更多 >