使用列表Python映射列数据框

时间:2017-07-27 11:00:19

标签: python list pandas

如何创建新列并设置值,这些值是将此数据帧与另一个对象(例如列表python列表)进行映射的结果?

我有pandas dataframe:

{'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]}

2 个答案:

答案 0 :(得分:3)

您可以在dict创建的dict comprehension之前使用map,列表的值必须是唯一的:

df = pd.DataFrame({'a': [15,10,11,9,7,8], 'b':['smth','smth','smth','smth', 'smth', 'smth']})

L = [[15,10], [11], [9,7,8]]
#https://stackoverflow.com/q/45349225/2901002
d = { v : i for i,vs in enumerate(L) for v in vs}
#alternative solution
#d = {v: i for i in range(len(L)) for v in L[i]}
print (d)
{7: 2, 8: 2, 9: 2, 10: 0, 11: 1, 15: 0}

df['new_column'] = df['a'].map(d)
print (df)
    a     b  new_column
0  15  smth           0
1  10  smth           0
2  11  smth           1
3   9  smth           2
4   7  smth           2
5   8  smth           2

答案 1 :(得分:0)

您可以在列表理解中使用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