如何按日期对表格的Date和DocNumber列排序并保存更改?
How to Sort Date Column and Update DocNumber Sequence
Hey Zahra, let's get this sorted out for you! It looks like you want to sort your table by the Date column in ascending order, and have the DocNumber column update to match the new sorted sequence. Below are step-by-step solutions for two common tools you might be using:
1. Using Excel or Google Sheets
If you're working with a spreadsheet tool, follow these steps:
- First, select your entire table (including the header row:
DateandDocNumber). - Go to the Data tab in the top menu, then click Sort.
- In the sort settings window:
- Set the Primary Key to
Date, Sort On to Values, and Order to A to Z (ascending order). - Click OK—your table will now be sorted by date, but the
DocNumbercolumn will still show the original values.
- Set the Primary Key to
- To update
DocNumberto match the new sequence:- Insert a temporary column next to
DocNumber(e.g., column C). - In cell C2, type
1, then in C3 type2. Select both cells, hover over the bottom-right corner until you see a small square, then drag down to fill the rest of the rows with consecutive numbers. - Copy the values from the temporary column, right-click on the
DocNumbercolumn, select Paste Special > Values to replace the old numbers. - Delete the temporary column when you're done.
- Insert a temporary column next to
2. Using Python with Pandas
If you prefer to handle this with code, here's a quick solution using the pandas library:
import pandas as pd # Create your original table as a DataFrame df = pd.DataFrame({ 'Date': ['2018-15-04', '2018-15-07', '2018-15-08', '2018-15-06', '2018-15-05'], 'DocNumber': [1, 2, 3, 4, 5] }) # Sort the DataFrame by the Date column in ascending order df_sorted = df.sort_values(by='Date', ascending=True).reset_index(drop=True) # Update DocNumber to be consecutive numbers starting from 1 df_sorted['DocNumber'] = df_sorted.index + 1 # Print the sorted result print(df_sorted) # Save the sorted table to a CSV file (you can change the file name as needed) df_sorted.to_csv('sorted_documents.csv', index=False)
Running this code will give you exactly the sorted table you're looking for, and save it to a CSV file if you need to keep the changes.
内容的提问来源于stack exchange,提问作者Zahra Bayat
相关产品推荐
相关产品推荐

