如何基于DataFrame行内两列条件为指定单元格赋值?
Fixing Your Pandas DataFrame Update Logic
Your core logic is on the right track, but there's a key issue with how you're checking for matching rows—Pandas doesn't allow using a DataFrame directly in an if condition (this will throw a ValueError because it can't reduce the DataFrame to a single boolean). Let's fix that and also address a deprecation issue with append().
Step-by-Step Corrected Implementation
Here's a robust version of your code that works as intended:
import pandas as pd # Define a boolean mask to identify rows matching your criteria mask = (df_['Camera'] == camera1) & (df_['Return'].isnull()) # Check if any rows match the mask if mask.any(): # Update the 'Return' column for all matching rows df_.loc[mask, 'Return'] = time_ else: # Append new row (using pd.concat instead of deprecated append()) # Convert dfin to a single-row DataFrame if it's a dict/list of values dfin_row = pd.DataFrame([dfin]) df_ = pd.concat([df_, dfin_row], ignore_index=True) # Save the updated DataFrame to CSV df_.to_csv(csv_file, index=False)
Key Improvements:
- Valid Condition Check: Using
mask.any()safely checks if there are any rows that meet your criteria (returnsTrueif at least one row matches the mask). - Deprecated
append()Replacement: Pandas'append()method is no longer recommended, so we usepd.concat()instead—this is the official way to add rows to a DataFrame moving forward. Ifdfinis already a single-row DataFrame, you can skip the conversion step. - Cleaner Code: Defining the mask once and reusing it makes the code more readable and avoids repeating the same filter logic.
Edge Cases to Consider:
- If multiple rows match your criteria (same
camera1with nullReturn), this code will update all of them withtime_. If you only want to update the first matching row, modify the mask tomask & (df_.index == df_[mask].index[0]). - Ensure
time_is stored in a format compatible with your CSV (e.g., a string like'2024-05-20 14:30:00').
内容的提问来源于stack exchange,提问作者Novato
相关产品推荐
相关产品推荐

