You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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 C and PF positions for each team (with a fallback if either is missing to avoid crashes).
  • Generate pairs:
    • First creates the C -> PF relationship as required.
    • Then creates PF -> [PG, SF, SG] pairs for all other positions in the team.
  • Clean file paths: Uses raw strings (r"path") to avoid issues with backslashes in Windows file paths.
  • Avoid index clutter: Adds index=False when 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:03:15