簡體   English   中英

根據列列表中的值對Pandas Dataframe進行切片

[英]Slicing Pandas Dataframe based on a value present in a column which is a list of lists

我有一個帶有一百萬行(id)的熊貓數據框,其中一列作為列表列表。 例如

df = pd.DataFrame({'id':[1,2,3,4],'token_list':[['a','b','c'],['c','d'], ['a','e','f'],['c','f']]})

我想創建一個包含所有唯一標記的字典-'a','b','c','e','f'(我已經作為單獨的列表)作為鍵以及每個鍵的所有ID與..相聯系。 例如,{'a':[1,3],'b':[1],'c':[1、2,4] ..}等等。

我的問題是有12000個這樣的令牌,我不想使用循環來遍歷第一幀的每一行。 並在似乎不起作用。

使用np.repeatnumpy.concatenate為第一平整,然后groupbylist和最后to_dict

a = np.repeat(df['id'], df['token_list'].str.len())
b = np.concatenate(df['token_list'].values)

d = a.groupby(b).apply(list).to_dict()
print (d)

{'c': [1, 2, 4], 'a': [1, 3], 'b': [1], 'd': [2], 'e': [3], 'f': [3, 4]}

詳情:

print (a)
0    1
0    1
0    1
1    2
1    2
2    3
2    3
2    3
3    4
3    4
Name: id, dtype: int64

print (b)
['a' 'b' 'c' 'c' 'd' 'a' 'e' 'f' 'c' 'f']
df.set_index('id')['token_list'].\
    apply(pd.Series).stack().reset_index(name='V').\
       groupby('V')['id'].apply(list).to_dict()
Out[359]: {'a': [1, 3], 'b': [1], 'c': [1, 2, 4], 'd': [2], 'e': [3], 'f': [3, 4]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM