簡體   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