【问题标题】:"None of [Index(['latitude', 'longitude'], dtype='object')] are in the [index]"“[Index(['latitude', 'longitude'], dtype='object')] 中没有一个在 [index] 中”
【发布时间】:2019-09-30 17:14:14
【问题描述】:

我有一个带有地理位置的 pandas 数据框,我正在尝试创建一个列并将一个函数传递给它,该函数将获取每个位置的 walkscores。

这是我的数据框:

df_test[['latitude', 'longitude']]

    latitude    longitude
0   50.673170   -120.322639
1   50.669597   -120.341833
2   50.650727   -120.150661
3   50.687545   -120.297688
4   50.772361   -122.811211
5   50.882304   -119.865000
6   50.643431   -120.362385
7   50.707459   -120.376297
8   50.708614   -120.409419
9   50.697850   -120.389101
10  50.659250   -119.998597

当我在单个变量上测试函数时,一切正常:

walkscore(df_test['latitude'][0], df_test['longitude'][0], key)

71

但是当我尝试将这个函数传递给整个数据集时,如下方式,我得到了一个错误:

df_test.loc['walkscore'] = df_test.loc[['latitude', 'longitude']].\
    apply(lambda x:
                    walkscore(x['latitude'], x['longitude'], apikey), axis='columns')

KeyError: "None of [Index(['latitude', 'longitude'], dtype='object')] are in the [index]"

我尝试重置索引,但没有帮助。我在这里做错了吗?

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    删除loc,因为需要查找列,而不是索引值:

    df_test['walkscore'] = df_test.\
        apply(lambda x: walkscore(x['latitude'], x['longitude'], apikey), axis='columns')
    

    用示例函数验证:

    apikey = 'aaa'
    def walkscore(x, y, apikey):
        return tuple((x, y))
    
    df_test['walkscore'] = df_test.\
        apply(lambda x: walkscore(x['latitude'], x['longitude'], apikey), axis='columns')
    
    print (df_test)
         latitude   longitude                                  walkscore
    0   50.673170 -120.322639                    (50.67317, -120.322639)
    1   50.669597 -120.341833  (50.669596999999996, -120.34183300000001)
    2   50.650727 -120.150661           (50.650727, -120.15066100000001)
    3   50.687545 -120.297688                   (50.687545, -120.297688)
    4   50.772361 -122.811211           (50.772361, -122.81121100000001)
    5   50.882304 -119.865000                      (50.882304, -119.865)
    6   50.643431 -120.362385                   (50.643431, -120.362385)
    7   50.707459 -120.376297                   (50.707459, -120.376297)
    8   50.708614 -120.409419          (50.708614000000004, -120.409419)
    9   50.697850 -120.389101                    (50.69785, -120.389101)
    10  50.659250 -119.998597                    (50.65925, -119.998597)
    

    【讨论】:

    • 感谢您的回复@jezrael。当我运行该函数时,它会在响应行中给我一个步行得分值列表,但是,当我查看 walkscore 列时,它的所有值都没有
    • @user4718221 - 如果使用我的示例函数def walkscore(x, y, apikey): return tuple((x, y)) 它工作吗?
    • 是的。我检查了 API 及其工作正常,它只是不会以某种方式将正确的结果放入数据框中
    • @user4718221 - 是的,我只想测试,如果使用我的自定义 walkscore 函数得到与我的答案相同的输出。
    • 没关系,我修好了。我有 print(walkscore) 而不是 return 所以它不会向数据框注册任何内容。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2019-09-03
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多