如何创建新列并设置值,该值是将此数据框与另一个对象映射为列表python实例列表的结果?

我有熊猫数据框:

{'a': [15,10,11,9,7,8], 'b':['smth','smth','smth','smth', 'smth', 'smth'].


和清单清单:

[[15,10], [11], [9,7,8]]


我想在数据框中创建新列,该列将包含3个大类,例如在列表中。

我的意思是,我想得到这个:

{'a': [15,10,11,9,7,8], 'b':['smth','smth','smth','smth', 'smth', 'smth',
'new_column': [0,0,1,2,2,2]}

最佳答案

您可以在列表理解中使用np.where

In [926]: import itertools

In [927]: l = np.array(list(itertools.zip_longest(*[[15,10], [11], [9,7,8]], fillvalue=0))).T

In [928]: df['new'] = [np.where(l == i)[0][0] for i in df.a.values]

In [929]: df
Out[929]:
    a     b  new
0  15  smth    0
1  10  smth    0
2  11  smth    1
3   9  smth    2
4   7  smth    2
5   8  smth    2

关于python - 使用列表Python映射列数据框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45348871/

10-11 21:05