Python 2.7 从数据帧创建三维平滑曲面打印

Python 2.7 从数据帧创建三维平滑曲面打印,python-2.7,pandas,Python 2.7,Pandas,我有一个数据帧z1,其条目如下: z1.ix[1:10,1:3] 2017-04-01 2017-05-01 2017-01-04 NaN 0.993549 2017-01-05 NaN NaN 2017-01-06 0.830973 0.978463 2017-01-09 0.926456 NaN 2017-01-10 0.998371 0.997590 2017-01

我有一个数据帧z1,其条目如下:

z1.ix[1:10,1:3]
            2017-04-01  2017-05-01
2017-01-04         NaN    0.993549
2017-01-05         NaN         NaN
2017-01-06    0.830973    0.978463
2017-01-09    0.926456         NaN
2017-01-10    0.998371    0.997590
2017-01-11    0.997539    0.999364
2017-01-12    NaN         0.989801
2017-01-13    0.999701    0.998526
2017-01-16    0.995119    0.998891
我正在尝试使用行索引作为X轴、列名作为Y轴和Z轴上的值创建曲面图

我尝试了以下方法:

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    x = z1.columns
    y = z1.index
    X, Y = np.meshgrid(x, y)
    Z = z1
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(X, Y, Z)
我发现以下错误:

TypeError: ufunc multiply cannot use operands with types dtype('float64') and dtype('<M8[ns]')

我认为其中一些库不支持datetime类型。 您应该首先将数据转换为适当的格式。 这是一个关于io的例子,它只是用于简单的复制粘贴数据帧

from io import StringIO
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

s = StringIO("""
            2017-04-01  2017-05-01
2017-01-04         NaN    0.993549
2017-01-05         NaN         NaN
2017-01-06    0.830973    0.978463
2017-01-09    0.926456         NaN
2017-01-10    0.998371    0.997590
2017-01-11    0.997539    0.999364
2017-01-12    NaN         0.989801
2017-01-13    0.999701    0.998526
2017-01-16    0.995119    0.998891""")
z1 = pd.DataFrame.from_csv(s, sep='\s+')


def string_date_to_numeric(li):
    series = pd.Series(li)
    datetime = pd.to_datetime(series)
    numeric = pd.to_numeric(datetime)
    return numeric


x = string_date_to_numeric(z1.columns)
y = string_date_to_numeric(z1.index)
X, Y = np.meshgrid(x, y)
print(X, Y)
Z = z1.values
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
fig.savefig('plot.png')
图:

之后可以重命名axis

ax.set_xticklabels(z1.columns)
ax.set_yticklabels(z1.index)

添加到代码示例中,您可以设置大小、格式和其他所有内容。
ax.set_xticklabels(z1.columns)
ax.set_yticklabels(z1.index)