满足指定条件时,如何用Pandas获取DataFrame的最后一行数据?
First, let's recreate the exact DataFrame from your provided table so we can work with a reproducible example:
import pandas as pd # Build the sample DataFrame data = { '1': [0, 30, 0, 62, 62, 62], '2': [0, 30, 0, 0, 30, 92], '3': [0, 0, 0, 0, 0, 92], '4': [50, 0, 0, 0, 50, 142], '1.1': [0, 0, 0, 62, 62, 62], '2.1': [0, 30, 0, 0, 30, 92], '3.1': [0, 0, 0, 0, 0, 92], '4.1': [50, 0, 0, 0, 50, 142] } df = pd.DataFrame(data, index=['w1', 'w2', 'd1', 'd2', 'Total', 'Cumulative']) df.index.name = 'WS'
Now, let's cover common scenarios for retrieving the last row based on different conditions:
Scenario 1: Get the last row of the entire DataFrame
If you just need the final row regardless of conditions, use iloc[-1]—this accesses the row at the last position in the DataFrame:
last_row = df.iloc[-1] # Output will be the 'Cumulative' row
Scenario 2: Get the last row that meets a column-specific condition
Suppose you want the last row where column '1' has a value greater than 0. First filter the DataFrame to keep only matching rows, then grab the last one:
# Filter rows where column '1' > 0 filtered = df[df['1'] > 0] # Get the last row of the filtered result last_matching_row = filtered.iloc[-1]
You can also condense this into a single line:
last_matching_row = df[df['1'] > 0].iloc[-1]
Pro tip: Always check if the filtered DataFrame isn't empty before accessing iloc[-1] to avoid an IndexError:
filtered = df[df['1'] > 0] if not filtered.empty: last_matching_row = filtered.iloc[-1] else: print("No rows satisfy the condition.")
Scenario 3: Get the last row with a specific index label
If you're targeting rows with a particular index name (like 'Cumulative'), use loc. If there are multiple rows with the same label, iloc[-1] will get the last occurrence:
# For a unique index label cumulative_row = df.loc['Cumulative'] # If multiple rows have the same label, get the last one last_cumulative_row = df.loc['Cumulative'].iloc[-1]
Scenario 4: Get the last row where any column meets a condition
For example, if you want the last row that has at least one non-zero value:
# Check if any value in the row is non-zero filtered = df[df.any(axis=1)] last_non_zero_row = filtered.iloc[-1]
These methods cover most common use cases. Adjust the condition in the filter step to match your specific requirements!
内容的提问来源于stack exchange,提问作者Dylan

