基于Pandas实现CSV父子依赖关系列构建的代码修改求助
Fixing Parent-Child Dependency Generation with Pandas
I see the issue with your current code—it's not properly grouping by Team and generating the required Parent-Child pairs. Let's adjust it to meet your exact requirements, including handling each team separately and creating all the necessary relationships.
Here's the corrected code:
import pandas as pd # Use raw string for file path to avoid escape character issues df = pd.read_csv(r"C:\Users\Desktop\nba.csv") # Initialize empty DataFrame to store final Parent-Child pairs result_df = pd.DataFrame(columns=['Parent', 'Child']) # Group data by Team to process each team separately for team, group in df.groupby('Team'): # Extract the C and PF positions for the current team try: center_pos = group[group['Position'] == 'C']['Position'].iloc[0] power_forward_pos = group[group['Position'] == 'PF']['Position'].iloc[0] except IndexError: # Handle case where a team is missing C or PF (optional but recommended) print(f"Warning: Team {team} is missing C or PF position, skipping.") continue # Get all other positions (excluding C and PF) other_positions = group[~group['Position'].isin(['C', 'PF'])]['Position'].tolist() # Create the C -> PF pair result_df = pd.concat([ result_df, pd.DataFrame({'Parent': [center_pos], 'Child': [power_forward_pos]}) ], ignore_index=True) # Create PF -> other positions pairs if other_positions: pf_pairs = pd.DataFrame({ 'Parent': [power_forward_pos] * len(other_positions), 'Child': other_positions }) result_df = pd.concat([result_df, pf_pairs], ignore_index=True) # Save the final result to CSV result_df.to_csv(r"C:\Users\Desktop\result.csv", index=False)
What this code does:
- Group by Team: Ensures we process each team's positions independently, which is critical since your dependency rules are per-team.
- Extract key positions: Grabs the
CandPFpositions for each team (with a fallback if either is missing to avoid crashes). - Generate pairs:
- First creates the
C -> PFrelationship as required. - Then creates
PF -> [PG, SF, SG]pairs for all other positions in the team.
- First creates the
- Clean file paths: Uses raw strings (
r"path") to avoid issues with backslashes in Windows file paths. - Avoid index clutter: Adds
index=Falsewhen saving to CSV so you don't get an extra index column in your output.
When you run this with your sample data, it will produce exactly the expected output:
Parent Child
C PF
PF PG
PF SF
PF SG
内容的提问来源于stack exchange,提问作者Sara Daniel
相关产品推荐
相关产品推荐

