pandas python pandas的转换器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12522963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:26:00  来源:igfitidea点击:

converters for python pandas

pythonpandas

提问by tomasz74

I have a .txt data where columns 6 and 7 are GPS position in the form:

我有一个 .txt 数据,其中第 6 列和第 7 列是以下形式的 GPS 位置:

50;18.5701400N,4;07.7693770E

When I read it by read_csv I try to convert it to cartesian coordinates by using converters. I wrote the function for converter

当我通过 read_csv 读取它时,我尝试使用转换器将其转换为笛卡尔坐标。我为转换器编写了函数

convertFunc = lambda x : float((x[0:5]+x[6:12]).replace(';','.'))
convert = {6:convertFunc,7:convertFunc}

when I use it on single value it works how I would like:

当我在单个值上使用它时,它的工作方式是我想要的:

convertFunc(myData.Lat[1])
Out [159]:  55.187110250000003

when I try to use it in read_csv it does not work

当我尝试在 read_csv 中使用它时它不起作用

myData = DataFrame(read_csv('~/data.txt', sep=',' names=['A', 'B', 'C', 'D', 'E', 'Lat', 'Long'],converters=convert))

I have an error:

我有一个错误:

...
convertFunc = lambda x : float((x[0:5] + x[6:12]).replace(';', '.'))
ValueError: invalid literal for float(): DGPS ongitu

I don't know where do it wrong or what I misunderstand in converters? Or maybe anyone knows good way (package) to work with GPS data in that form?

我不知道哪里做错了或者我对转换器有什么误解?或者也许有人知道以这种形式处理 GPS 数据的好方法(包)?

(I think it can be some problem with lambdaWhen I want to apply my function to the column I have an error: TypeError: only length-1 arrays can be converted to Python scalars)

(我认为这可能是有些问题,lambda当我想要我的功能应用到专栏中,我有一个错误:TypeError: only length-1 arrays can be converted to Python scalars

回答by nneonneo

That converter is a bit hacky; might I recommend something more robust like this?

那个转换器有点笨拙;我可以推荐一些像这样更强大的东西吗?

def convert_dmds(s):
    deg, min = s[:-1].split(';')
    sign = 1 if s[-1] in 'NE' else -1
    return sign * (float(deg) + float(min) / 60.0)

def convert_gps(s):
    lat, lon = s.split(',')
    return (convert_dmds(lat), convert_dmds(lon))

Also, the error indicates that you are trying to convert something that is clearly not a GPS string -- a header row, perhaps?

此外,该错误表明您正在尝试转换显然不是 GPS 字符串的内容——也许是标题行?

回答by Wouter Overmeire

Your converter is not ok.

你的转换器不行。

In [67]: convertFunc = lambda x : float((x[0:5]+x[6:12]).replace(';','.'))

In [68]: convertFunc('4;07.7693770E')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
...
ValueError: invalid literal for float(): 4.07.693770

On top of a dodgy converter, i think you apply the converter to the wrong column (look at the exception you get).

在狡猾的转换器之上,我认为您将转换器应用于错误的列(看看您得到的异常)。