Python Pandas多级索引添加行并执行角度相关运算求助
Hey there! As someone who stumbled through similar Pandas tasks when I was starting out, I’ll walk you through a straightforward, efficient way to tackle this. Let’s turn your original DataFrame into the expanded version with angle-based trigonometric calculations.
Step 1: Break Down the Core Task
You want to take each row in your original DataFrame, create 360 copies (one for every angle from 0 to 359), then compute new X/Y values using cosine/sine functions that combine the angle with the original X/Y values.
Step 2: Set Up Your Tools & Sample Data
First, let’s get our imports and sample DataFrame ready (matching your example):
import pandas as pd import numpy as np # Your original indexed DataFrame df = pd.DataFrame({ 'X': [50, 30], 'Y': [100, 70] }, index=['Data', 'Data2'])
Step 3: Expand Rows with All Angles
We’ll first attach a list of all angles (0-359) to every row, then use explode() to turn each list item into its own row. This creates the Cartesian product of your original rows and angles—exactly what you need:
# Add a column containing all angles (0 to 359) to each row df['Angle'] = [np.arange(360) for _ in range(len(df))] # Explode the list into individual rows, keeping the original index expanded_df = df.explode('Angle', ignore_index=False) # Convert Angle values to integers (explode keeps them as numpy ints initially) expanded_df['Angle'] = expanded_df['Angle'].astype(int)
After this step, each original row will have 360 entries, each with a unique angle from 0 to 359.
Step 4: Calculate New X/Y with Trigonometric Functions
Now we’ll compute the updated X/Y values. Let’s use a common formula as an example (adjust this to match your exact requirements):
new_X = original_X + (some_radius * cos(angle_in_radians))new_Y = original_Y + (some_radius * sin(angle_in_radians))
We’ll use vectorized operations (way faster than looping through rows):
# Convert angles from degrees to radians (required for numpy trig functions) angle_rad = np.radians(expanded_df['Angle']) # Replace this with your actual radius or variable radius = 5 # Compute new X and Y values expanded_df['X'] = expanded_df['X'] + radius * np.cos(angle_rad) expanded_df['Y'] = expanded_df['Y'] + radius * np.sin(angle_rad)
If you want to keep the original X/Y values alongside the new ones, just rename the columns first (e.g., expanded_df['Original_X'] = expanded_df['X'] before calculating the new X).
Step 5: Match Your Sample’s Index Format (Optional)
To make the index look like your example (with duplicate index labels hidden), you can mask the repeats when displaying:
# Create a mask for the first occurrence of each index mask = expanded_df.index.duplicated() # Set duplicate index labels to empty strings for cleaner display expanded_df.index = expanded_df.index.where(~mask, '')
This will show the index name only once per original row group, just like your sample output.
Quick Performance Tip
Always prefer Pandas/Numpy vectorized operations over looping through rows—they’re exponentially faster, especially when you’re generating 360 rows per original entry.
内容的提问来源于stack exchange,提问作者David

