编写拆分DataFrame的函数及处理地点转移数据的技术咨询
Hey there, let's break down how to tackle both of your tasks step by step.
1. Function to Generate Independent DataFrames from Each Row
If you need to take every row in a pandas DataFrame and turn it into its own separate DataFrame (super useful for row-specific processing that expects a full DataFrame input), here's a clean implementation:
import pandas as pd def row_to_single_df(row): # Convert the row into a 1-row DataFrame, keeping original column names return pd.DataFrame([row.values], columns=row.index) # Example usage with your transfer data transfer_data = { 'Origin': ['A', 'B', 'C'], 'Dest': ['B', 'C', 'B'], 'Time': ['Mon', 'Wed', 'Fri'] } transfer_df = pd.DataFrame(transfer_data) # Loop through each row to get individual DataFrames for row_num, row in transfer_df.iterrows(): single_row_df = row_to_single_df(row) print(f"Row {row_num} as standalone DataFrame:") print(single_row_df) print("---")
This function works by taking a row (from iterrows()), wrapping its values in a list (so pandas interprets it as a single row), and using the original row's index to preserve column names. Each output is a fully functional DataFrame with one row—no weird Series conversions needed.
2. Analyzing Location Transfers with the Distance Matrix
Now let's work on enriching your transfer data with distances and calculating totals. First, let's set up our data correctly:
# Your transfer records transfer_df = pd.DataFrame({ 'Origin': ['A', 'B', 'C'], 'Dest': ['B', 'C', 'B'], 'Time': ['Mon', 'Wed', 'Fri'] }) # Distance matrix (index and columns are location names for easy lookup) distance_matrix = pd.DataFrame({ 'A': [0, 8, 11], 'B': [8, 0, 6], 'C': [11, 6, 0] }, index=['A', 'B', 'C'])
Add Travel Distance to Each Transfer
To get the distance for each Origin→Dest pair, we can use apply() to look up values from the matrix:
def lookup_distance(row): # Grab the value from the matrix using Origin as index and Dest as column return distance_matrix.loc[row['Origin'], row['Dest']] # Add a new 'Distance' column to the transfer DataFrame transfer_df['Distance'] = transfer_df.apply(lookup_distance, axis=1) print("Transfer DataFrame with calculated distances:") print(transfer_df)
This will output:
Origin Dest Time Distance 0 A B Mon 8 1 B C Wed 6 2 C B Fri 6
Calculate Total Distance Traveled
If you want the sum of all transfers, it's as simple as:
total_traveled = transfer_df['Distance'].sum() print(f"Total distance traveled across all transfers: {total_traveled} units")
Which gives us 8 + 6 + 6 = 20 units total.
Bonus: Handle Same-Location Transfers
Since your distance matrix has 0 values for same-location pairs (like A→A), this code automatically handles those cases without any extra checks—perfect for your allowed continuous transfers.
内容的提问来源于stack exchange,提问作者jp334

