繁体   English   中英

将ecdf函数应用于数据框和绘图中的每一列

[英]apply ecdf function to each column in dataframe and plot

我想将我的自定义ecdf函数应用于数据框中的每一列,然后根据返回的x,y值绘制ecdf

自定义函数:

def ecdf(df):
    n = len(df)
    x = np.sort(df)
    y = np.arange(1, n+1)/n
    return x, y

我在for循环中的尝试:

for col in sj_interpol_data.columns:
   x_col, y_col = ecdf(col)
   ax = plt.figure()
   ax = plt.plot(x_col, y_col, marker='.', linestyle='none')
   ax = plt.margins=(0.02)
   plt.show()

编辑为包含错误:

AxisError                                 Traceback (most recent call last)
<ipython-input-75-d03c4fa0a973> in <module>()
      2 #design a for-loop which applies ecdf() on each column in df and plots them separately
      3 for col in sj_interpol_data.columns:
----> 4     x_col, y_col = ecdf(col)
      5     ax = plt.figure()
      6     ax = plt.plot(x_col, y_col, marker='.', linestyle='none')

<ipython-input-32-353fb281e367> in ecdf(df)
      4     n = len(df)
      5     #define x values - sorted values in array
----> 6     x = np.sort(df)
      7     #define y values - maps location of each datapoint WR to their percentiles
      8     y = np.arange(1, n+1)/n

C:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in sort(a, axis, kind, order)
    845     else:
    846         a = asanyarray(a).copy(order="K")
--> 847     a.sort(axis=axis, kind=kind, order=order)
    848     return a
    849 

AxisError: axis -1 is out of bounds for array of dimension 0

关于如何编写此函数的建议,以便可以将其应用于数据帧中的所有列并自动在for循环中绘制?

您将列名传递给ecdf函数,但您想将数据帧传递给它,至少这是函数定义所指示的。

我想出了答案。 我在ecdf函数中使用df.sort_values(),该函数使用熊猫对值而不是numpy进行排序

所以修改后的函数是:

def ecdf(df):
    n = len(df)
    x = df.sort_values()
    y = np.arange(1, n+1)/n
    return x, y

应用了for循环(如上所示)后,输出结果为数据帧中的每一列生成了单独的ecdf图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM