Pandas行内多值校验与替换问题求助:现有代码未生效
Fixing Your Pandas DataFrame Value Replacement Issues
Hey there! Let's sort out this pandas DataFrame problem together. Your original code didn't work for a couple of small but important reasons—let's break it down and fix it with clean, standard code that meets both your requirements.
Step 1: Set Up Example Data
First, let's recreate your DataFrame (plus an extra all-0 row to test the second requirement):
import pandas as pd data = [ [0, 10, 0, 0], [1, 1, 1, 1], [0, 12, 0, 0], [0, 0, 0, 0], # Test case for requirement 2 [0, 13, 0, 0] ] df = pd.DataFrame(data, columns=['open', 'high', 'low', 'close'])
Step 2: Implement Requirement 1
When open, low, close are all 0 and high is not 0, replace those three columns with the high value:
# Define the exact condition for requirement 1 condition1 = (df['open'] == 0) & (df['low'] == 0) & (df['close'] == 0) & (df['high'] != 0) # Replace the columns—note the list for column selection and reshaping to match dimensions df.loc[condition1, ['open', 'low', 'close']] = df.loc[condition1, 'high'].values.reshape(-1, 1)
Step 3: Implement Requirement 2
When all four columns are 0, set open/low to 1 and close/high to 10:
# Define the condition for all values being 0 (shorter than checking each column individually) condition2 = (df == 0).all(axis=1) # Assign the new values to the respective columns df.loc[condition2, ['open', 'low']] = 1 df.loc[condition2, ['close', 'high']] = 10
Step 4: Check the Result
Run print(df) and you'll get the corrected DataFrame:
open high low close 0 10 10 10 10 1 1 1 1 1 2 12 12 12 12 3 1 10 1 10 4 13 13 13 13
Why Your Original Code Failed
- Incomplete conditions: You only checked
open == 0, but didn't verifylow/closewere also 0 or exclude rows wherehighwas 0. This would have incorrectly modified all-0 rows too. - Column selection syntax: In
loc, multiple columns need to be passed as a list (['open', 'low', 'close']) instead of comma-separated names. - Dimension mismatch: Assigning a 1-dimensional Series directly to multiple columns causes a shape error—using
reshape(-1,1)converts it to a 2D array that matches the column structure.
内容的提问来源于stack exchange,提问作者Marx Babu
相关产品推荐
相关产品推荐

