Lon_X Lat_Y
5,234234 6,3234234
5,234234 6,3234234
5,234234 6,3234234
5,234234 6,3234234
5,234234 6,3234234我有像上面那样的熊猫/数据中心的GPS坐标。但是,它们使用逗号分隔符。利用熊猫将这些转换成浮动GPS坐标的最佳方法是什么?
for item in frame.Lon_X:
float(item.replace(",", ".")) # makes the conversion but does not store it back我尝试过迭代项函数,但是看起来非常慢,并给出了一个警告,我不太明白:
for index, value in frame.Lon_X.iteritems():
frame.Lon_X[index] = float(value.replace(",", "."))请参阅文档中的注意事项:从ipykernel导入的http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy作为应用程序
发布于 2016-12-30 22:13:52
您可以使用应用程序图
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发布于 2016-12-30 22:35:31
您可以将熊猫的矢量化方法应用到一个轴上:
def to_float_inplace(x):
x[:] = x.str.replace(',', '.').astype(float)
df.apply(to_float_inplace)发布于 2016-12-30 22:59:47
可以跳过使用apply,直接用replace方法替换为regex=True
df.replace(',', '.', regex=True).astype(float)https://stackoverflow.com/questions/41403301
复制相似问题