Search code examples
pythonpandasdataframematplotlibsurface

Python: pandas 3d dataframe into X,Y,Z


I have my csv data read by pd.read_csv (https://www.pkks.de/contourN.dat):

         0        1         2
0     -3.0 -3.00000 -0.001395
1     -3.0 -2.97647 -0.001410
2     -3.0 -2.95294 -0.001421
3     -3.0 -2.92941 -0.001426
4     -3.0 -2.90588 -0.001427
...    ...      ...       ...
65531  3.0  2.90588 -0.001427
65532  3.0  2.92941 -0.001426
65533  3.0  2.95294 -0.001421
65534  3.0  2.97647 -0.001410
65535  3.0  3.00000 -0.001395

which represents (x,y,z) coordinates. How must I convert these data into X, Y, Z variables to plot a surface with matplotlib:

ax.plot_surface(X, Y, Z, ...)

Solution

  • import pandas as pd
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    
    data = pd.read_csv('your_file.csv', sep=',', names=['X', 'Y', 'Z'], index_col=False)
    
    x_num = len(data['X'].unique())
    y_num = len(data['Y'].unique())
    
    x = data['X'].values.reshape(x_num, -1)
    y = data['Y'].values.reshape(y_num, -1)
    z = data['Z'].values.reshape((x_num, y_num))
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, z)