0

我希望找到数据框中输入定义的键值的索引的确切值,下面是我试图获取它的代码。

data_who = pd.DataFrame({'index':data['index'], 'Publisher_Key':data['Key']})

下面是我的 O/P 数据框:

在此处输入图像描述

如果假设我给一个输入说 100 作为键值,我想得到索引值的 O/P,即 Goat,我应该在我的代码中做什么?

PS:标签编码后的数据中标签过多,所以想知道标签的值对应于哪个类别。

4

2 回答 2

2

如果index是一列,那么您可以执行以下操作:

data.loc[data['Key'] == 100, 'index'].iloc[0]
>>> 'Zebra'

或其他选项:

data[data['Key'] == 100]['index'].iloc[0]
>>> 'Zebra'

如果 index 是数据帧的索引,则替换['index'].index.

附带说明:您不应该index在 pandas 中命名列,它本身就是一个概念,以这种方式命名列可能会产生误导。

于 2021-02-27T07:05:22.010 回答
1

我建议三种方法来做到这一点:

  1. 使用熊猫:
data_who.loc[data_who['key'] == 100, 'index'].values[0]
>>> 'Goat'
  1. 使用 python 字典:
who_dict = dict(zip(data_who['key'], data_who['index']))
who_dict[100]
>>> 'Goat'
  1. 最后,如果您使用LabelEncoderfrom skeern,它可以对值进行逆变换:
le = LabelEncoder()
le.fit(animals) # fit on the list of animals
le.inverse_transform([100])
于 2021-02-27T07:12:25.153 回答