You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script:移除数组NaN值后无法打印新数组至表格的问题求助

Fixing NaN Removal and Table Display in Pine Script

Let’s break down the issues in your code and fix them step by step:

1. Problem with NaN Removal Loop

Your current loop to remove NaN values has a critical flaw: when you remove an element from the array while looping forward, the indices of the remaining elements shift left. This means you’ll skip checking the element that moves into the position of the one you just removed.

Corrected NaN Removal Code

Instead, loop backward from the end of the array to the start. This way, removing elements doesn’t affect the indices of the elements you haven’t checked yet:

SRprices = array.new_float(array.size(sr_levs))
for xi = 0 to array.size(sr_levs) - 1
    array.set(SRprices, xi, array.get(sr_levs, xi))

// Fixed: Loop backward to avoid skipping elements
for k = array.size(SRprices) - 1 downto 0
    if na(array.get(SRprices, k))
        array.remove(SRprices, k)

2. Problem with the Second Table Display

Your commented table code fails for two main reasons:

  • Using var initializes the table once with the initial size of SRprices, but after removing NaNs, the array size is smaller (and may change over time).
  • The table isn’t updated to reflect the new array size or content after modifications.

Corrected Table Code

Use a persistent table (with var), but clear existing content, update the row count to match the current array size, then repopulate the cells:

// Create persistent table (only initialized once)
var table SRtable = table.new(position.top_right, columns = 1, rows = 0, 
bgcolor = color.rgb(210,210,210), border_width = 2, border_color = color.white, frame_color = color.black, frame_width = 2)

// Clear existing cells to prepare for new data
table.clear(SRtable)

// Update table row count to match the cleaned array size
table.set_row_count(SRtable, array.size(SRprices))

// Populate the table with cleaned values
for xii = 0 to array.size(SRprices) - 1
    table.cell(table_id = SRtable, column = 0, row = xii , text_size=size.small, 
    text = str.tostring(array.get(SRprices, xii)))

Bonus: Optimized Array Initialization (Optional)

Instead of copying the entire array first then removing NaNs, you can filter values during initialization to save a step:

SRprices = array.new_float()
for xi = 0 to array.size(sr_levs) - 1
    val = array.get(sr_levs, xi)
    if not na(val)
        array.push(SRprices, val)

This directly builds the cleaned array without needing a separate removal loop.


内容的提问来源于stack exchange,提问作者Mori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:12:42