尝试将小数点添加到浮点时出现Keyerror

2024-05-10 08:02:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在我正在处理的数据集中,纬度和经度的一些值缺少小数点,为此,我创建了一个函数来处理这个问题

我在第6行得到错误:

data.loc[data[lat_col] > 90, lat_col] /= 1000

我假设第7行会给我同样的错误

错误:

KeyError: "None of [Float64Index([55.6902,     0.0,     0.0,     0.0, 55.6775,     0.0,     0.0,\n                  0.0,     0.0,     0.0,\n              ...\n                  0.0,     0.0,     0.0, 55.9379, 55.9379, 55.9379, 55.9379,\n              55.9379, 55.9378,     0.0],\n             dtype='float64', length=143820)] are in the [columns]"

资料

    latitude    longitude
0   12.57220    55.69020
1   0.00000     0.00000
2   0.00000     0.00000
4   0.00000     0.00000
5   12.57700    55.67750
6   0.00000     0.00000
7   0.00000     0.00000
8   0.00000     0.00000
9   0.00000     0.00000
10  0.00000     0.00000
11  0.00000     0.00000
12  0.00000     0.00000
14  12.58440    55.67970
15  12.58230    55.67930
16  12.58478    55.67996
17  12.58477    55.67996
18  12.59170    55.67980
...

作用

def clean_latitude_longitude(data, lat_col, lon_col):
    """Fixes lat & lon values, some of them are missing decimal points.
    """
    #data = data.copy()

    data.loc[data[lat_col] > 90, lat_col] /= 1000
    data.loc[data[lon_col] > 180, lon_col] /= 1000
    return data

dff = clean_latitude_longitude(df, df["latitude"], df["longitude"])

Tags: of数据cleandfdata错误colloc
1条回答
网友
1楼 · 发布于 2024-05-10 08:02:39

错误是因为您正在作为参数传递整个系列,而不是列名,因此函数loc将在列名中查找您正在传递的列的值,并且没有这样命名的列,这是错误的原因,因此请尝试更改:

clean_latitude_longitude(df, df["latitude"], df["longitude"])

致:

clean_latitude_longitude(df, "latitude", "longitude")

相关问题 更多 >