如何对DataFrame每行执行条件运算?求解行级if语句正确实现方式
Hey there! Let's get that DataFrame logic working properly. The issue with your current code comes from two main things: using and instead of pandas-compatible boolean operators, and trying to apply a standard Python if statement to an entire Series instead of leveraging pandas' vectorized operations (which are way faster and cleaner).
Let's break down the correct approaches:
1. Recommended: Use numpy.where (Vectorized, Fast)
This is the best method for most cases, especially with larger datasets, since it operates on the entire Series at once instead of looping row-by-row.
import numpy as np import pandas as pd # Assuming your DataFrame is already defined df['720-1080'] = np.where( (df['position'] > 720) & (df['position'] < 1080), # The condition df['position'] - 360, # Value if condition is True np.nan # Value if condition is False (replace with 0/df['position'] if needed) )
Note: We use & instead of and here because we're working with boolean Series—and expects single boolean values, not arrays of booleans.
2. Use pandas.loc for Explicit Indexing
If you prefer a more step-by-step approach, you can create a boolean mask and update only the rows that meet your condition:
# Initialize the new column with NaN (or another default value) df['720-1080'] = np.nan # Create a mask for rows where position is between 720 and 1080 position_mask = (df['position'] > 720) & (df['position'] < 1080) # Update only the rows that match the mask df.loc[position_mask, '720-1080'] = df.loc[position_mask, 'position'] - 360
3. Row-wise apply (Not Recommended for Large Data)
If you really need to use a row-by-row if statement (this is slower for big DataFrames), you can use apply with a custom function:
def adjust_position(row): if 720 < row['position'] < 1080: return row['position'] - 360 else: return np.nan # Replace with your preferred default value df['720-1080'] = df.apply(adjust_position, axis=1)
Remember: axis=1 tells pandas to apply the function to each row instead of each column.
Why Your Original Code Didn't Work:
- You used
andinstead of&—pandas requires&for element-wise boolean operations on Series. - The
if row in (...)syntax doesn't work here becausedf['position']>720 and df['position']<1080returns a boolean Series, not a list of rows to check against.
内容的提问来源于stack exchange,提问作者1lk4

