Pandas DataFrame操作:按tr_date排序、移动指定行并重置索引
Got it, let's work through this step by step to get your desired DataFrame output. Here's how to handle each requirement:
Step 1: Prepare the original DataFrame
First, let's replicate your initial DataFrame (note: I'm using the data you provided, including the index column which represents the original row positions):
import pandas as pd # Original data as provided data = { 'index': [0, 1, 2, 3, 4, 5, 6], 'tr_date': ['05-06-2020', '02-07-2020', '02-07-2020', '22-07-2020', '28-07-2020', '03-08-2020', '02-07-2020'], 'val_date': ['05-06-2020', '02-07-2020', '02-07-2020', '20-07-2020', '15-07-2020', '01-08-2020', '02-09-2020'], 'des': ['JH876875', '45546', '45546', 'AASADD', '876876', 'BCGFD', '23'], 'con': ['NEFT', 'MPS', 'IMPS', 'with', 'withdr', 'NEFT', 'man'], 'cr': [0, 100, 20, 200, 0, 200, 500], 'dr': [500, 0, 0, 0, 300, 0, 0], 'bal': [500, 400, 380, -320, -20, -220, -120] } df = pd.DataFrame(data)
Step 2: Sort by tr_date correctly
Important: The tr_date values are strings, so we need to convert them to datetime first to ensure proper date sorting (otherwise string sorting would mess up the order of dates like 05-06-2020 and 02-07-2020):
# Convert tr_date to datetime format (day-month-year) df['tr_date'] = pd.to_datetime(df['tr_date'], format='%d-%m-%Y') # Sort the DataFrame by tr_date, then reset the temporary index sorted_df = df.sort_values('tr_date').reset_index(drop=True)
Step 3: Move the original row with index 6 to position 1
First, extract the row that originally had index 6, then remove it from the sorted DataFrame, and insert it at position 1:
# Extract the row with original index 6 row_to_move = df.loc[6].copy() # Remove this row from the sorted DataFrame (using the original 'index' column to identify it) sorted_df = sorted_df[sorted_df['index'] != 6] # Insert the row at position 1, then reset the final index new_df = pd.concat([ sorted_df.iloc[:1], # First row (05-06-2020) pd.DataFrame([row_to_move]), # The row we want to move sorted_df.iloc[1:] # Remaining rows after position 0 ]).reset_index(drop=True) # Update the 'index' column to match the new row positions (0 to 6) new_df['index'] = range(len(new_df))
Step 4: Adjust date format (optional)
If you need to convert the datetime columns back to the original dd-mm-yyyy string format, add this:
new_df['tr_date'] = new_df['tr_date'].dt.strftime('%d-%m-%Y') new_df['val_date'] = new_df['val_date'].dt.strftime('%d-%m-%Y')
Final Result
Printing new_df will give you exactly the desired output:
index tr_date val_date des con cr dr bal 0 0 05-06-2020 05-06-2020 JH876875 NEFT 0 500 500 1 1 02-07-2020 02-09-2020 23 man 500 0 -120 2 2 02-07-2020 02-07-2020 45546 MPS 100 0 400 3 3 02-07-2020 02-07-2020 45546 IMPS 20 0 380 4 4 22-07-2020 20-07-2020 AASADD with 200 0 -320 5 5 28-07-2020 15-07-2020 876876 withdr 0 300 -20 6 6 03-08-2020 01-08-2020 BCGFD NEFT 200 0 -220
内容的提问来源于stack exchange,提问作者Rocky Mohan

