Python二维数组基准归一化(Base Norming)实现方法咨询
2D Array Normalization with Row-Wise Base Values
Got it, let's work through this 2D array normalization problem together. You already nailed the 1D version, so extending that logic to 2D just needs a bit of row-wise handling to keep the first row and column intact.
Let's Break Down the Requirements
- Keep the first row (headers) and first column (country names) exactly as they are.
- For each data row (starting from the second row):
- The second element (2019 value) becomes 100 (our baseline).
- Every subsequent element in the row is converted to a percentage relative to that row's 2019 value (i.e.,
(current_value / row_base) * 100), rounded to an integer to match your sample output.
Full Implementation Code
Here's a straightforward way to achieve this:
# Original 2D array lista = [['countries', 2019, 2021, 2022],['aruba', 2,13,8],['barbados', 6,34,39],['japan', 12,8,16]] # Initialize the normalized array with the unchanged header row listaNormed = [lista[0]] # Process each data row starting from the second row for row in lista[1:]: # Extract the country name and the base value (2019 data for this country) country_name = row[0] base_value = row[1] # Start building the normalized row: country name + baseline 100 normalized_row = [country_name, 100] # Calculate normalized values for the rest of the row's elements for value in row[2:]: # Compute the percentage and convert to integer (matches your sample rounding) normalized_value = int((value / base_value) * 100) normalized_row.append(normalized_value) # Add the processed row to our result array listaNormed.append(normalized_row) # Print the final normalized array print(listaNormed)
What This Code Does
- Preserve Headers: We start by adding the original first row directly to
listaNormedsince we don't want to modify it. - Row-by-Row Processing: For each country row:
- We grab the country name and its 2019 value (our baseline for that row).
- We initialize the new row with the country name and the baseline value 100.
- For each subsequent year's value, we calculate how it compares to the 2019 baseline, scale to a percentage, and convert to an integer (to match your sample output's whole numbers).
- Build the Result: Each processed row gets added to
listaNormed.
Running This Code Will Output Exactly What You Want:
[['countries', 2019, 2021, 2022], ['aruba', 100, 650, 400], ['barbados', 100, 566, 650], ['japan', 100, 66, 133]]
Quick Note on Rounding
If you wanted more precise decimal values instead of integers, you could replace int() with round() (e.g., round((value / base_value) * 100)). For your sample inputs, this would still give the same whole numbers, but it handles cases where you might need fractional percentages.
内容的提问来源于stack exchange,提问作者LabCoat
相关产品推荐
相关产品推荐

