Python代码优化:如何用前一行数值替换输出中的\N?
Solution: Fill \N with Previous Valid Value
Got it, let's fix this missing value filling issue. Your original code extracts the second column but doesn't keep track of the last valid number to replace those \N entries. Here's a straightforward adjustment that gets you exactly the output you want:
Step-by-Step Code Implementation
# Your raw data (formatted with newlines as implied by your split('\n') logic) data = """xxx,1593,7 \N yyy,1094,4 ddd,1015,0,2 zzz,1576,5 \N aaa,1037,6""" list_data = data.split('\n') last_valid_value = None # Track the most recent valid number we've encountered for line in list_data: parts = line.split(',') # Check if this is a full data line (has at least 3 comma-separated values) if len(parts) >= 3: current_value = parts[1] last_valid_value = current_value # Update our tracking variable print(current_value) else: # This is a \N line—use the last valid number we saved if last_valid_value is not None: print(last_valid_value) else: # Edge case: handle first-line missing values if needed (your data doesn't have this) print(line)
Expected Output
Running this code will produce your desired result:
1593 1593 1094 1015 1576 1576 1037
Key Details
- We use the variable last_valid_value to persist the most recent valid number from the second column of a complete data line.
- When we hit a line with just
\N(or any line with fewer than 3 comma-separated parts), we output the saved last_valid_value instead of the missing marker. - The
last_valid_value is not Nonecheck is a safeguard for edge cases where the first line might be a missing value (your dataset doesn't have this, but it makes the code more robust).
内容的提问来源于stack exchange,提问作者Iriel
相关产品推荐
相关产品推荐

