Skip to main content
 首页 » 编程设计

python之替换数据框Python中的值

2025年02月15日9freeliver54

Lon_X        Lat_Y 
5,234234     6,3234234 
5,234234     6,3234234 
5,234234     6,3234234 
5,234234     6,3234234 
5,234234     6,3234234 

我在上面的 pandas/dataframe 中有 GPS 坐标。然而,这些使用逗号分隔符。使用 pandas 将这些转换为 float GPS 坐标的最佳方法是什么?

for item in frame.Lon_X: 
    float(item.replace(",", ".")) # makes the conversion but does not store it back 

我试过 iteritems 函数,但看起来很慢,并给了我一个我不太明白的警告:

for index, value in frame.Lon_X.iteritems(): 
    frame.Lon_X[index] = float(value.replace(",", ".")) 

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy from ipykernel import kernelapp as app

请您参考如下方法:

您可以使用 applymap :

df[["Lon_X", "Lat_Y"]] = df[["Lon_X", "Lat_Y"]].applymap(lambda x: float(x.replace(",", "."))) 
df 


以下是关于这些替代方法的一些基准测试,to_float_inplace 比所有其他方法快得多:

数据:

df = pd.DataFrame({"Lon_X": ["5,234234" for i in range(1000000)], "Lat_Y": ["6,3234234" for i in range(1000000)]}) 

# to_float_inplace 
def to_float_inplace(x): 
    x[:] = x.str.replace(',', '.').astype(float) 
 
%timeit df.apply(to_float_inplace) 
# 1 loops, best of 3: 269 ms per loop 
 
# applymap + astype 
%timeit df.applymap(lambda x: x.replace(",", ".")).astype(float) 
# 1 loops, best of 3: 1.26 s per loop 
 
# to_float 
def to_float(x): 
    return x.str.replace(',', '.').astype(float) 
 
%timeit df.apply(to_float) 
# 1 loops, best of 3: 1.47 s per loop 
 
# applymap + float 
%timeit df.applymap(lambda x: float(x.replace(",", "."))) 
# 1 loops, best of 3: 1.75 s per loop 
 
# replace with regex 
%timeit df.replace(',', '.', regex=True).astype(float) 
# 1 loops, best of 3: 1.79 s per loop