如何处理Numpy坐标数组与DataFrame坐标列数据并整理至字典?
Got it, let's break this down step by step. It sounds like your for loop was probably overwriting values instead of building out the nested structure you need—hence why you only saw single values popping out. Let's fix this and tackle your extra question too.
Step 1: Setup Example Data (Matching Your Scenario)
Let's assume your data looks something like this (adjust to match your actual numpy array and DataFrame):
import numpy as np import pandas as pd # Your numpy array with coordinates (lon, lat or lat, lon—adjust as needed) coords_np = np.array([[116.397, 39.908], [0.0, 0.0], [121.473, 31.230], [0.0, 12.34], [104.066, 30.659]]) # Your DataFrame where each row has a cluster of coordinate indices df = pd.DataFrame({'clusters': [[0, 2], [3, 4]]})
Step 2: Correct Loop to Clean Coordinates & Preserve Structure
Here's the fixed code that keeps the nested cluster structure, removes 0.0 values (or full 0.0 coordinates—see notes below), and populates your dictionary:
# Initialize your target dictionary with an empty list for cleaned clusters result_dict = {'cleaned_clusters': []} for cluster in df['clusters']: # Create an empty list for the cleaned coordinates in this cluster cleaned_cluster = [] for idx in cluster: # Pull the coordinate from the numpy array and convert to a list coord = coords_np[idx].tolist() # Choose the cleaning logic that fits your needs: # Option 1: Remove individual 0.0 values from the coordinate (e.g., [0.0, 12.34] becomes [12.34]) # cleaned_coord = [x for x in coord if x != 0.0] # if cleaned_coord: # Only add if there's something left after cleaning # cleaned_cluster.append(cleaned_coord) # Option 2: Remove entire coordinates that are all 0.0 (keep non-zero points) if not all(x == 0.0 for x in coord): cleaned_cluster.append(coord) # Add the cleaned cluster to your dictionary's list result_dict['cleaned_clusters'].append(cleaned_cluster) # Check the result print(result_dict)
Why Your Original Loop Failed
Chances are you were doing something like result_dict['cleaned_clusters'] = cleaned_cluster instead of result_dict['cleaned_clusters'].append(cleaned_cluster), or you didn't initialize the inner cleaned_cluster list per iteration. This would overwrite the dictionary value every time instead of building out the nested structure.
Step 3: Handling Your Extra Question (Collect All Lat/Lon Values)
If you want to extract all cleaned latitude and longitude values (either as a flat list or separate lists), here's how:
# Option A: Flatten all cleaned coordinates into a single list all_cleaned_coords = [coord for cluster in result_dict['cleaned_clusters'] for coord in cluster] # Option B: Separate longitude and latitude into individual lists all_lons = [coord[0] for cluster in result_dict['cleaned_clusters'] for coord in cluster] all_lats = [coord[1] for cluster in result_dict['cleaned_clusters'] for coord in cluster] # Option C: Add cleaned coordinates directly to your DataFrame as a new column df['cleaned_coords'] = result_dict['cleaned_clusters']
Quick Note for String '0.0' Values
If your numpy array has string values like '0.0' instead of floats, add a conversion step when pulling coordinates:
coord = [float(x) for x in coords_np[idx].tolist()]
内容的提问来源于stack exchange,提问作者Takusui

