循环遍历DataFrame并按event类型填充对应xCordAdjusted、yCordAdjusted数据至字典的实现问题
Fixing Your DataFrame to Dictionary Mapping Code
Let's break down what's going wrong with your current code, then walk through a corrected implementation that will populate your league_data dictionary as expected.
Key Issues in Your Original Code
- Wrong DataFrame iteration:
for data in season_dfloops through your DataFrame's column names (likeseason,event), not the actual rows of data. So your checks againstevent_typesare comparing column names to event values—this will never match, hence your empty lists. - Incorrect event check: Even if you were looping rows,
if data in event_typesis checking the entire row object against your event list, not the value stored in theeventcolumn of that row. - Nonsensical x-range condition:
if 'x' in range(0,100)compares the string"x"to integers 0-99, which will always beFalse. This line is blocking all your append operations entirely. - Adding strings instead of values:
append(['xCordAdjusted'])adds the literal string"xCordAdjusted"(wrapped in a list) to your x/y lists, not the numeric coordinate value from the row.
Corrected Implementation (Row-by-Row Iteration)
This approach uses iterrows() to loop through each row of your DataFrame, which is straightforward for smaller datasets:
# Initialize the target dictionary with empty lists league_data = { 'SHOT': {'x': [], 'y': []}, 'GOAL': {'x': [], 'y': []}, 'MISS': {'x': [], 'y': []} } target_events = ['SHOT', 'GOAL', 'MISS'] # Iterate over each row (ignore the index with "_") for _, row in season_df.iterrows(): current_event = row['event'] # Only process events we care about if current_event in target_events: # Extract the adjusted coordinate values x_adjusted = row['xCordAdjusted'] y_adjusted = row['yCordAdjusted'] # Append to the corresponding lists in the dictionary league_data[current_event]['x'].append(x_adjusted) league_data[current_event]['y'].append(y_adjusted)
More Efficient Version (Using groupby)
For larger datasets, iterrows() can be slow. Using pandas' groupby is a more optimized approach:
league_data = {} target_events = ['SHOT', 'GOAL', 'MISS'] # First filter the DataFrame to only include our target events filtered_season_df = season_df[season_df['event'].isin(target_events)] # Group by event type and extract coordinate lists for event, group in filtered_season_df.groupby('event'): league_data[event] = { 'x': group['xCordAdjusted'].tolist(), 'y': group['yCordAdjusted'].tolist() }
What This Does
- Both versions will take your sample rows (like the MISS event with
xCordAdjusted=61andyCordAdjusted=29) and add those values to the correct lists inleague_data. - After running, your
league_data['MISS']['x']will contain[61],league_data['SHOT']['x']will contain[54, 40], and so on.
内容的提问来源于stack exchange,提问作者jhh19
相关产品推荐
相关产品推荐

