Python pandas修改df_OmanAirTO的FuelFlow列值未生效求助
Hey there! Let's break down what's going on with your code and get those FuelFlow values updated properly.
The Problem with Your Current Code
Your loop is iterating over each value in df_OmanAirTO.FuelFlow, but you're not actually saving the modified values back to the DataFrame. When you run df_OmanAirTO.FuelFlow/2.2046226218, it calculates a new Series with the divided values, but you don't assign this result back to df_OmanAirTO.FuelFlow—so the original data stays untouched. Also, looping through individual rows in pandas is usually inefficient (pandas is designed for vectorized operations instead of slow row-by-row loops).
Fix 1: Vectorized Conditional Assignment (Recommended!)
Pandas excels at vectorized operations—this is the fastest and most "pandas-idiomatic" way to do what you want. You have two great options here:
import numpy as np # Option 1: Using numpy.where for clear conditional logic df_OmanAirTO['FuelFlow'] = np.where( df_OmanAirTO['FuelFlow'] > 5800, df_OmanAirTO['FuelFlow'] / 2.2046226218, df_OmanAirTO['FuelFlow'] ) # Option 2: Using pandas .loc to target specific rows (even cleaner!) df_OmanAirTO.loc[df_OmanAirTO['FuelFlow'] > 5800, 'FuelFlow'] /= 2.2046226218
- The first option checks every value: if it's over 5800, divide it; otherwise keep it as-is, then assigns the whole updated set back to the column.
- The second uses
.locto directly target only the rows whereFuelFlowis greater than 5800, then divides those values in place.
Fix 2: Using apply() (Function-Based Approach)
If you prefer a more explicit, function-driven method, you can use apply() to run your logic on each value in the column:
def adjust_fuel_flow(value): if value > 5800: return value / 2.2046226218 else: return value df_OmanAirTO['FuelFlow'] = df_OmanAirTO['FuelFlow'].apply(adjust_fuel_flow)
This applies your custom logic to every value and assigns the updated results back to the FuelFlow column.
Fix 3: Fixing Your Original Loop (Not Recommended)
If you really want to make your loop work (though it's not ideal for large DataFrames), you need to track the index and assign each modified value back to its correct position:
for idx, value in df_OmanAirTO['FuelFlow'].items(): if value > 5800: df_OmanAirTO.loc[idx, 'FuelFlow'] = value / 2.2046226218 # No need for elif—values <=5800 stay as they are
Just note: this will be slower than the vectorized methods above, especially if your dataset is big.
After trying any of these fixes, run print(df_OmanAirTO.FuelFlow) and you'll see the updated values!
内容的提问来源于stack exchange,提问作者L. Nieuwendijk

