如何在Python 3.7的DataFrame中按条件替换列值?
Solution for Conditional Value Replacement in Pandas DataFrame
Got it, let's break down how to implement your two replacement rules efficiently in pandas. Here's a step-by-step approach that matches exactly what you need:
Step 1: Set up your sample DataFrame
First, let's recreate your input data so you can test the code directly:
import pandas as pd # Sample DataFrame data = { 'XX': [0, 1, 3, -1, 5, 7, -1, 6], 'Date': ['2016-05-01']*8, 'Time': ['19:00:00', '18:00:00', '17:00:00', '16:00:00', '15:00:00', '14:00:00', '13:00:00', '12:00:00'] } df = pd.DataFrame(data) # Your lookup dictionary (included the 13:00 entry as seen in your example) lookup_dict = {'13:00:00': 1, '01:00:00':1, '02:00:00':4, '23:00:00':0}
Step 2: Apply the specific conditional replacement first
We want to handle the special case first (XX=-1 and Time='16:00:00') to make sure it doesn't get overwritten by the dictionary mapping later. Use pandas loc to target exactly those rows:
# Replace XX with 2 where conditions are met df.loc[(df['XX'] == -1) & (df['Time'] == '16:00:00'), 'XX'] = 2
Step 3: Use the lookup dictionary for remaining -1 values
Now handle all other rows where XX is still -1, mapping their Time values to the corresponding value in your dictionary:
# Replace remaining XX=-1 entries using the lookup dict df.loc[df['XX'] == -1, 'XX'] = df.loc[df['XX'] == -1, 'Time'].map(lookup_dict)
Step 4: Verify the result
If you print the DataFrame now with print(df), you'll get exactly the output you wanted:
XX Date Time 0 0 2016-05-01 19:00:00 1 1 2016-05-01 18:00:00 2 3 2016-05-01 17:00:00 3 2 2016-05-01 16:00:00 4 5 2016-05-01 15:00:00 5 7 2016-05-01 14:00:00 6 1 2016-05-01 13:00:00 7 6 2016-05-01 12:00:00
Key Notes:
- Order matters: We handle the special case first because if we used the dictionary mapping first, the 16:00:00 entry would be replaced with whatever value is in your dict (if any) instead of 2.
locis safe: Usinglocensures we only modify the exact rows/columns we intend to, avoiding accidental changes to other data.mapis efficient: It quickly matches Time values to your dictionary, which is perfect for bulk replacements.
内容的提问来源于stack exchange,提问作者Clueless_Doggo
相关产品推荐
相关产品推荐

