我正试图在新列中输出基于数据集中另一列标签的整数值(标签/类(。实际上,我是通过为每个类创建新的列(数字列标题(来实现的,其中包含布尔值,这样我就可以使用这些列来创建带有数字值的新类列。但我试着用字典来做,我认为这是一个好的、更快的方法。
如果我运行这样的代码:
x=df['Item_Type'].value_counts()
item_type_mapping={}
item_list=x.index
for i in range(0,len(item_list)):
item_type_mapping[item_list[i]]=i
它生成字典,但如果我运行:
df['Item_Type']=df['Item_Type'].map(lambda x:item_type_mapping[x])
或
df['New_column']=[item_type_mapping[item] for item in data.Item_Type]
显示KeyError=None
有人知道为什么会发生这种情况吗?我觉得这很奇怪,因为字典已经创建,我可以通过我的变量看到它
感谢
编辑1@傅立叶我有这个专栏:
| Item_type|
| -------- |
| Nino |
| Nino |
| Nino |
| Pasquale |
| Franco |
| Franco |
然后我需要相同的列或新的列来显示:
| Item_type| New_column |
| -------- | ---------- |
| Nino | 1 |
| Nino | 1 |
| Nino | 1 |
| Pasquale | 2 |
| Franco | 3 |
| Franco | 3 |
您的代码对我来说很有效,但您试图做的事情已经由pandas作为类别数据提供了。
df = pd.DataFrame({'Item_Type': list('abca')})
df['New_column'] = df.Item_Type.astype('category').cat.codes
结果:
Item_Type New_column
0 a 0
1 b 1
2 c 2
3 a 0