如何无循环将DataFrame中0-360的经度值转换为-180至180?
Solution for Converting Longitude Values to -180 to 180 Range
You can use pandas' vectorized operations to achieve this without any for loops. Here are two straightforward approaches:
Approach 1: Using pandas.loc
This method initializes the new column with original values, then updates only the entries that need conversion.
import pandas as pd # Sample DataFrame df = pd.DataFrame({'lon': [1, 10, 15, 250, 360]}) # Create new column with original values df['new_lon'] = df['lon'] # Update values greater than 15 by subtracting 360 df.loc[df['lon'] > 15, 'new_lon'] = df['lon'] - 360
Approach 2: Using numpy.where
This one-liner conditionally applies the conversion using numpy.where, which is efficient for element-wise operations.
import pandas as pd import numpy as np # Sample DataFrame df = pd.DataFrame({'lon': [1, 10, 15, 250, 360]}) # Conditionally compute new_lon df['new_lon'] = np.where(df['lon'] > 15, df['lon'] - 360, df['lon'])
Result
Both methods will produce the desired output:
| lon | new_lon |
|---|---|
| 1 | 1 |
| 10 | 10 |
| 15 | 15 |
| 250 | -110 |
| 360 | 0 |
Explanation
- Values ≤15 are kept as-is since they already fall within the -180 to 180 range.
- Values >15 (which in your dataset are 250-360) are converted by subtracting 360, which shifts them into the negative longitude range (e.g., 250 - 360 = -110, 360 - 360 = 0).
- Both approaches use vectorized operations, which are far more efficient than loops for large DataFrames.
内容的提问来源于stack exchange,提问作者Billiam
相关产品推荐
相关产品推荐

