首页 > 解决方案 > 将数据映射到地面实况列表

问题描述

我在以下 Python 列表中有基本事实数据:

ground_truth = [(A,16), (B,18), (C,36), (A,59), (C,77)]

所以任何值来自:

0-16 gets mapped to A, 
17-18 maps to B, 
19-36 maps to C,
37-59 maps to A 
60-77 maps to C
and so on

我正在尝试从像这样的数字映射时间序列输入

[9,15,29,32,49,56, 69]  to its respective classes like:
[A, A, C, C, A, A,  C]

假设我的输入是 Pandas 系列,例如:

in = pd.Series([9,15,29,32,49,56, 69])

我如何进入该系列[A, A, C, C, A, A, C]

标签: pandas

解决方案


这是我的方法:

gt = pd.DataFrame(ground_truth)

# bins for cut
bins = [0] + list(gt[1])

# categories
cats = pd.cut(pd.Series([9,15,29,32,49,56, 69]), bins=bins, labels=False)

# labels
gt.loc[cats, 0]

0    A
0    A
2    C
2    C
3    A
3    A
4    C
Name: 0, dtype: object

或者,不创建新数据框:

labels = np.array([x for x,_ in ground_truth])
bins = [0] + [y for _,y in ground_truth]        

cats = pd.cut(pd.Series([9,15,29,32,49,56, 69]), bins=bins, labels=False)

labels[cats]

这使:

array(['A', 'A', 'C', 'C', 'A', 'A', 'C'], dtype='<U1')

推荐阅读