Pandas:使用pythonmap()意外输出数据类型

2024-06-28 11:32:56 发布

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

我在上使用map()1.数据帧. 我试图将字符串映射到某个特定的整数。你知道吗

>>> df_train['gold_label'].head()
0          neutral
1    contradiction
2       entailment
3    contradiction
4    contradiction
Name: gold_label, dtype: object
>>> dic = {'entailment': 0, 'neutral': 1, 'contradiction': 2}
>>> df_train['gold_label'] = df_train['gold_label'].map(dic)
>>> df_train['gold_label'].head()
0    1.0
1    2.0
2    0.0
3    2.0
4    2.0
Name: gold_label, dtype: float64

我希望得到一个整数结果,但实际上是float64。 但是,我使用另一个相同格式的数据集(上面是dev数据集),结果将是预期的整数。你知道吗

以上程序哪里出了问题?你知道吗


Tags: 数据namemapdftrain整数headlabel
1条回答
网友
1楼 · 发布于 2024-06-28 11:32:56

正如Akshay所提到的,如果在dataframe中发现字典映射之外有一个值,那么结果值将是'NaN',并导致float64结果。你知道吗

> a
array(['neutral', 'contradiction', 'entailment', 'contradiction',
   'contradiction'],
  dtype='|S13')
> b
array(['neutral', 'contradiction', 'entailment', 'contradiction',
   'contradiction', 'test'],
  dtype='|S13')
> d = pd.DataFrame(a, columns=['gold_label'])
> d2 = pd.DataFrame(b, columns=['gold_label'])
> dic = {'contradiction': 2, 'entailment': 0, 'neutral': 1}
> d['gold_label'].map(dic)
 0    1
 1    2
 2    0
 3    2
 4    2
 Name: gold_label, dtype: int64
 > d2['gold_label'].map(dic)
 0    1.0
 1    2.0
 2    0.0
 3    2.0
 4    2.0
 5    NaN
 Name: gold_label, dtype: float64

相关问题 更多 >