![](/img/trans.png)
[英]A list and a dataframe mapping to get a column value in python pandas
[英]Mapping column dataframe with list Python
如何創建新列並設置值,該值是將此數據框與另一個對象映射為列表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]}
您可以使用map
通過dict
通過創建dict comprehension
,列表的值必須是唯一的:
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
您可以在列表np.where
中使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.