Python数据帧索引作为XY坐标的元组

Python数据帧索引作为XY坐标的元组,python,pandas,dictionary,gps,coordinates,Python,Pandas,Dictionary,Gps,Coordinates,我的函数collectHUC获取XY坐标,并为1000个站点构建一个名为stationsXY的HUC代码字典。键是元组,类似于('41.462605','74.387089')和值类似于020000600。此过程需要时间,因此我将stationsXY转换为数据帧,并将其保存为以下内容以供以后使用: xy = pd.DataFrame.from_dict(stationsXY, orient='index') xy.to_csv('xy_huc.csv', index=False) 这里是一个问

我的函数
collectHUC
获取XY坐标,并为1000个站点构建一个名为
stationsXY
的HUC代码字典。
是元组,类似于
('41.462605','74.387089')
类似于
020000600
。此过程需要时间,因此我将
stationsXY
转换为数据帧,并将其保存为以下内容以供以后使用:

xy = pd.DataFrame.from_dict(stationsXY, orient='index')
xy.to_csv('xy_huc.csv', index=False)
这里是一个问题,当用

xy_coor = pd.read_csv('xy_huc.csv', index_col=0, header=None)
数据帧
xy_coor
有两列,第0列表示xy坐标,第1列表示HUC代码,通过将第0列设置为索引,索引格式现在是
string
,而不是
tuple
。到目前为止,我已经尝试过这些方法:

  • 读取csv文件,从列中将索引设置为多索引

    xy_coor = pd.read_csv('xy_huc.csv', index_col=0, header=None)
    xy = pd.DataFrame(xy_coor, index=pd.MultiIndex.from_tuples(xy_coor.index))
    
    但我有这个错误

    TypeError: Expected tuple, got str
    
  • 读取带有
    索引的csv\u col=False
    ,将索引设置为零列

    xy_coor = pd.read_csv('xy_huc.csv', index_col=False, header=None)
    xy = pd.DataFrame(stations_xy, index=pd.MultiIndex.from_tuples(xy_coor[0]))
    
    但是
    xy
    索引采用这种形式

  • 我愿意以保存文件时使用的格式检索该文件。欢迎提出任何建议/建议


    谢谢,有多种方法可以做到这一点,但我认为最简单的方法是将x和y保存为单独的列

    另一种方法是解析元组字符串,例如:

    def back_to_tuple(input_string):
        # remove punctuation but not comma 
        punctuation = "(/')"
        for punc in punctuation:
            input_string = input_string.replace(punc, '') 
    
        # split on comma -> list 
        input_string = input_string.split(',')
    
        # split on comma -> list 
        input_string = input_string.split(',')
    
        return input_string
    
    
    您还可以将xy元组保存为以“;”分隔的字符串:

    def tuple_to_string(input_tuple)
        return ';'.join(input_tuple)
    
    然后像这样检索它:

    def back_to_tuple(input_string):
        return tuple(input_string.split(';'))
    

    有多种方法可以做到这一点,但我认为最简单的方法是将x和y保存为单独的列

    另一种方法是解析元组字符串,例如:

    def back_to_tuple(input_string):
        # remove punctuation but not comma 
        punctuation = "(/')"
        for punc in punctuation:
            input_string = input_string.replace(punc, '') 
    
        # split on comma -> list 
        input_string = input_string.split(',')
    
        # split on comma -> list 
        input_string = input_string.split(',')
    
        return input_string
    
    
    您还可以将xy元组保存为以“;”分隔的字符串:

    def tuple_to_string(input_tuple)
        return ';'.join(input_tuple)
    
    然后像这样检索它:

    def back_to_tuple(input_string):
        return tuple(input_string.split(';'))