Python 如何在数据帧中按名称将函数应用于特定列

Python 如何在数据帧中按名称将函数应用于特定列,python,pandas,Python,Pandas,我有一个包含GPS坐标的列的数据框。我想将以度数秒为单位的列转换为十进制。例如,我有一个名为“lat_-sec”和“long_-sec”的两列,它们的格式为186780.8954N。我尝试编写一个函数,将字符串中的最后一个字符保存为方向,将其数字部分除以以获得十进制度数,然后将这两个字符连接在一起以获得新格式。然后,我尝试在数据框中按名称查找列,并对其应用函数 python新手,在这方面找不到其他资源。我认为我没有正确地创建我的函数。我在里面有“坐标”这个词,因为我不知道该怎么称呼我要分解的值。

我有一个包含GPS坐标的列的数据框。我想将以度数秒为单位的列转换为十进制。例如,我有一个名为“lat_-sec”和“long_-sec”的两列,它们的格式为186780.8954N。我尝试编写一个函数,将字符串中的最后一个字符保存为方向,将其数字部分除以以获得十进制度数,然后将这两个字符连接在一起以获得新格式。然后,我尝试在数据框中按名称查找列,并对其应用函数

python新手,在这方面找不到其他资源。我认为我没有正确地创建我的函数。我在里面有“坐标”这个词,因为我不知道该怎么称呼我要分解的值。 我的数据如下所示:

long_sec
635912.9277W
555057.2000W
581375.9850W
581166.2780W


df = pd.DataFrame(my_array)

def convertDec(coordinate):
    decimal = float(coordinate[:-1]/3600)
    direction = coordinate[-1:]
    return str(decimal) + str(direction)

df['lat_sec'] = df['lat_sec'].apply(lambda x: x.convertDec())

My error looks like this:
Traceback (most recent call last):
  File "code.py", line 44, in <module>
    df['lat_sec'] = df['lat_sec'].apply(lambda x: x.convertDec())
  File "C:\Python\Python37\lib\site-packages\pandas\core\frame.py", line 2917, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Python\Python37\lib\site-packages\pandas\core\indexes\base.py", line 2604, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 129, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index_class_helper.pxi", line 91, in pandas._libs.index.Int64Engine._check_type
KeyError: 'lat_sec'
长\u秒
635912.9277W
555057.2000W
581375.9850W
581166.2780W
df=pd.DataFrame(my_数组)
def convertDec(坐标):
十进制=浮点(坐标[:-1]/3600)
方向=坐标[-1:]
返回str(十进制)+str(方向)
df['lat_-sec']=df['lat_-sec'].apply(lambda x:x.convertDec())
我的错误如下所示:
回溯(最近一次呼叫最后一次):
文件“code.py”,第44行,在
df['lat_-sec']=df['lat_-sec'].apply(lambda x:x.convertDec())
文件“C:\Python\Python37\lib\site packages\pandas\core\frame.py”,第2917行,在\uu getitem中__
indexer=self.columns.get_loc(键)
文件“C:\Python\Python37\lib\site packages\pandas\core\index\base.py”,第2604行,在get\u loc中
返回self.\u引擎。获取\u loc(self.\u可能\u cast\u索引器(键))
pandas.\u libs.index.IndexEngine.get\u loc中的文件“pandas\\u libs\index.pyx”,第108行
pandas.\u libs.index.IndexEngine.get\u loc中第129行的文件“pandas\\u libs\index.pyx”
pandas.\u libs.index.Int64Engine.\u check\u type中第91行的文件“pandas\\u libs\index\u class\u helper.pxi”
KeyError:“lat_sec”
通过执行
float(坐标[:-1]/3600)
您将
str
除以
int
,这是不可能的,您可以做的是将
str
转换为
float
,然后将其除以整数
3600
,从而获得
float
输出

其次,您没有正确使用
apply
,并且没有将函数应用到
lat_sec

import pandas as pd

df = pd.DataFrame(['635912.9277W','555057.2000W','581375.9850W','581166.2780W'],columns=['long_sec'])

#function creation
def convertDec(coordinate):
    decimal = float(coordinate[:-1])/3600
    direction = coordinate[-1:]
    return str(decimal) + str(direction)

#if you just want to update the existing column 
df['long_sec'] = df.apply(lambda row: convertDec(row['long_sec']), axis=1)

#if you want to create a new column, just change to the name that you want
df['lat_sec'] = df.apply(lambda row: convertDec(row['long_sec']), axis=1) 

#OUTPUT
    long_sec
0   176.64247991666667W
1   154.18255555555555W
2   161.49332916666665W
3   161.43507722222225W

如果不希望以浮点形式输出,而希望以整数形式输出,只需将
float(坐标[:-1])/3600更改为
int(float(坐标[:-1])/3600)
在上面的代码中,在
convertDec
方法内,还存在以下错误:

decimal = float(coordinate[:-1]/3600)
您需要先将
坐标
转换为浮点,然后再将其除以3600

因此,上面的代码应该如下所示:

import pandas as pd

# Your example dataset
dictCoordinates = {
    "long_sec" : ["111111.1111W", "222222.2222W", "333333.3333W", "444444.4444W"],
    "lat_sec"  : ["555555.5555N", "666666.6666N", "777777.7777N", "888888.8888N"]
}

# Insert your dataset into Pandas DataFrame
df = pd.DataFrame(data = dictCoordinates)

# Your conversion method here
def convertDec(coordinate):
    decimal = float(coordinate[:-1]) / 3600 # Eliminate last character, then convert to float, then divide it with 3600
    decimal = format(decimal, ".4f") # To make sure the output has 4 digits after decimal point
    direction = coordinate[-1] # Extract direction (N or W) from content
    return str(decimal) + direction # Return your desired output

# Do the conversion for your "long_sec"
df["long_sec"] = df.apply(lambda x : convertDec(x["long_sec"]), axis = 1)

# Do the conversion for your "lat_sec"
df["lat_sec"] = df.apply(lambda x : convertDec(x["lat_sec"]), axis = 1)

print(df)

就这样。希望这有帮助。

好吧,您似乎没有名为
lat\u sec
的专栏。尝试并
打印(df.head())
要查看数据框的外观,通常会尝试在问题中包含任何数据/输入的最小示例,以便我们可以从问题中复制/粘贴以测试和再现问题。@lostCode我在尝试时遇到了与上述类似的错误that@Itay我把它打印出来了,我确实有一个同名的专栏你的问题现在只显示一个名为
long_sec
您刚刚复制了给定的答案。我有自己的答案,我有自己的代码。仅仅因为我的代码有相同的变量名、相同的函数名和相同的算法,并不意味着我复制了给定的答案。