【问题标题】:Why am I recieving key error after slicing my data? [duplicate]为什么我在切片数据后收到密钥错误? [复制]
【发布时间】:2019-12-16 10:12:44
【问题描述】:

我有一个切片数据的代码,然后假设根据列计算不同的索引。

我的代码运行良好,但今天我不得不对数据进行不同的切片,从那时起,每当我尝试计算索引时都会遇到 keyerror。

很遗憾,我无法分享我的原始数据,但我希望这段代码可以帮助理解这里发生的事情。

这是我的代码和一些解释:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df_plants = pd.read_csv('my_data')

#My data contains columns with numerical data and their column title is numbers
#here I have changed the numbers titles into float 
float_cols = [float(i) for i in df_plants.columns.tolist()[4:] if type(i)==str]
df_plants.columns.values[4:] = float_cols

#detector edges removal
#Here my goal is to remove some of the columns that has wrong data.
#this part was added today and might be the reason for the problem
cols = df_plants.columns.tolist()
df_plants=df_plants[cols[:4] + cols[11:]].copy()

#Trying to calculte indices:
filter_plants['NDVI']=(filter_plants['801.03']-filter_plants['680.75'])/(filter_plants['801.03']+filter_plants['680.75'])

KeyError: '801.03'

为了解决这个问题,我尝试在计算前再次添加这一行:

float_cols = [float(i) for i in df_plants.columns.tolist()[4:] ]
df_plants.columns.values[4:] = float_cols

但我仍然收到密钥错误。

我的最终目标是能够使用我认为与更改列类型有关的索引进行计算

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    尝试将最后一行更改为:

    filter_plants['NDVI']=(filter_plants[801.03]-filter_plants[680.75])/(filter_plants[801.03]+filter_plants[680.75])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多