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
。到目前为止,我已经尝试过这些方法:
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(';'))