我有一個資料框:
import pandas as pd
data = {'id':[1,2,3],
'tokens': [[ 'in', 'the' , 'morning',
'cat', 'run', 'today', 'very', 'quick'],['dog', 'eat', 'meat', 'chicken', 'from', 'bowl'],
['mouse', 'hides', 'from', 'a', 'cat']]}
df = pd.DataFrame(data)
我還有一個索引串列串列。
lst_index = [[3, 4, 5], [0, 1, 2], [2, 3, 4]]
我想創建一個包含列陣列中的元素的tokens列。此外,元素由 中的索引獲取lst_index。所以它將是:
id tokens new
0 1 [in, the, morning, cat, run, today, very, quick] [cat, run, today]
1 2 [dog, eat, meat, chicken, from, bowl] [dog, eat, meat]
2 3 [mouse, hides, from, a, cat] [from, a, cat]
uj5u.com熱心網友回復:
使用簡單的串列推導:
lst_index = [[3, 4, 5], [0, 1, 2], [2, 3, 4]]
df['new'] = [[l[i] for i in idx] for idx,l in zip(lst_index, df['tokens'])]
輸出:
id tokens new
0 1 [in, the, morning, cat, run, today, very, quick] [cat, run, today]
1 2 [dog, eat, meat, chicken, from, bowl] [dog, eat, meat]
2 3 [mouse, hides, from, a, cat] [from, a, cat]
uj5u.com熱心網友回復:
您可以按如下方式遍歷字典和串列來獲取new列:
data = {'id':[1,2,3],
'tokens': [[ 'in', 'the' , 'morning',
'cat', 'run', 'today', 'very', 'quick'],['dog', 'eat', 'meat', 'chicken', 'from', 'bowl'],
['mouse', 'hides', 'from', 'a', 'cat']]}
lst_index = [[3, 4, 5], [0, 1, 2], [2, 3, 4]]
l = []
for i in range(len(data["tokens"])):
l.append([])
for j in range(len(lst_index[i])):
l[i].append(data["tokens"][i][lst_index[i][j]])
data["new"] = l
print(data)
輸出:
{'id': [1, 2, 3], 'tokens': [['in', 'the', 'morning', 'cat', 'run', 'today', 'very', 'quick'], ['dog', 'eat', 'meat', 'chicken', 'from', 'bowl'], ['mouse', 'hides', 'from', 'a', 'cat']], 'new': [['cat', 'run', 'today'], ['dog', 'eat', 'meat'], ['from', 'a', 'cat']]}
uj5u.com熱心網友回復:
這可能不是最有效的解決方案,但它有效:
df['new'] = [[token[i] for i in index] for token, index in zip(df['tokens'], lst_index)]
id tokens new
0 1 [in, the, morning, cat, run, today, very, quick] [cat, run, today]
1 2 [dog, eat, meat, chicken, from, bowl] [dog, eat, meat]
2 3 [mouse, hides, from, a, cat] [from, a, cat]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496098.html
