You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无循环将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:

lonnew_lon
11
1010
1515
250-110
3600

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:35:31