DataFrame数据处理:替换空值并将指定列移至末尾
Got it, let's work through this problem step by step to get your desired DataFrame. Here's a practical implementation using pandas:
Step 1: Recreate the Input DataFrame
First, let's replicate the input data you provided:
import pandas as pd # Build the input DataFrame as per your example data = { 'ID': ['A1', 'B1', 'C1', 'D1'], '1': ['ABC', 'ABC', 'ABC', 'ABC'], '2': ['RED1', 'OR1', 'WHITE1', 'BLUE1'], '3': ['RED2', 'OR2', 'WHITE2', 'BLUE2'], '4': ['RED3', 'OR3', 'WHITE3', 'BLUE3'], '5': ['RED4', 'OR4', 'WHITE4', 'BLUE4'], 'col0': [10, 40, 50, 20], 'col1': [20, None, 34, None], 'col2': [None, None, 35, None], 'col3': [None, None, 57, None], 'col4': [None, None, 78, None], 'col5': [None, None, 98, None], 'col6': [None, None, None, None] } df = pd.DataFrame(data)
Step 2: Fill None Values with Target Columns
We'll write a row-wise function to replace missing values in col0-col6 using values from columns 2,3,4,5 in order:
def fill_missing(row): # Grab the values we'll use to fill missing entries fill_values = row[['2', '3', '4', '5']].tolist() fill_pos = 0 # Process each column in col0 to col6 col_names = [f'col{i}' for i in range(7)] updated_cols = [] for val in row[col_names]: if pd.isna(val) and fill_pos < len(fill_values): updated_cols.append(fill_values[fill_pos]) fill_pos += 1 else: updated_cols.append(val) # Update the row with the new values row[col_names] = updated_cols return row # Apply the function to every row df_filled = df.apply(fill_missing, axis=1)
Step 3: Rearrange and Rename Columns
Now we'll move the original 2,3,4,5 columns to the end and rename them to NEW1-NEW4:
# Define the final column order final_columns = ['ID', '1'] + [f'col{i}' for i in range(7)] + ['NEW1', 'NEW2', 'NEW3', 'NEW4'] # Rename columns and reorder the DataFrame df_final = df_filled.rename(columns={ '2': 'NEW1', '3': 'NEW2', '4': 'NEW3', '5': 'NEW4' })[final_columns]
Step 4: View the Result
Printing df_final will give you the desired output:
ID 1 col0 col1 col2 col3 col4 col5 col6 NEW1 NEW2 NEW3 NEW4 0 A1 ABC 10 20 RED1 RED2 RED3 RED4 None RED1 RED2 RED3 RED4 1 B1 ABC 40 OR1 OR2 OR3 OR4 None None OR1 OR2 OR3 OR4 2 C1 ABC 50 34 35 57 78 98 None WHITE1 WHITE2 WHITE3 WHITE4 3 D1 ABC 20 BLUE1 BLUE2 BLUE3 BLUE4 None None BLUE1 BLUE2 BLUE3 BLUE4
Note: Your expected output shows col6 as 99 for row 2, but the input has None there and we've used up all fill values from columns 2-5. If you need to set a specific value for remaining missing entries, you can add an extra condition in the fill_missing function.
内容的提问来源于stack exchange,提问作者Rashmi

