You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于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 (returns True if at least one row matches the mask).
  • Deprecated append() Replacement: Pandas' append() method is no longer recommended, so we use pd.concat() instead—this is the official way to add rows to a DataFrame moving forward. If dfin is 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 camera1 with null Return), this code will update all of them with time_. If you only want to update the first matching row, modify the mask to mask & (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:28:11