我有一个包含以下值的数据框
Keyword Synonyms
0 fuzz [hair, copper, pig, bull, cop, blur]
1 napkins [table]
2 rationalizations [systematization, rationalization]
3 grandmasters [grandmaster]
4 rehearsing [practice]
为了在以后的步骤中创建下拉菜单,我如何将“关键字”列中的值附加到同义词列中每个列表的开头?
我的代码如下:
df['Synonyms'] = pd.concat([df['Keyword'].append(df['Synonyms'])
答案 0 :(得分:3)
列表理解如何?在python3中,您可以使用扩展的可迭代解压缩功能来有效地创建新列表。
# df['Synonyms'] = [[x, *y] for x, y in df[['Keyword'], 'Synonyms']].values]
df['Synonyms'] = [[x, *y] for x, y in zip(df['Keyword'], df['Synonyms'])]
df
Keyword Synonyms
0 fuzz [fuzz, hair, copper, pig, bull, cop, blur]
1 napkins [napkins, table]
2 rationalizations [rationalizations, systematization, rationaliz...
3 grandmasters [grandmasters, grandmaster]
4 rehearsing [rehearsing, practice]
这是map
的有趣替代品:
k = iter(df['Keyword'].tolist())
df['Synonyms'] = df['Synonyms'].map(lambda x: [next(k), *x])
df
Keyword Synonyms
0 fuzz [fuzz, hair, copper, pig, bull, cop, blur]
1 napkins [napkins, table]
2 rationalizations [rationalizations, systematization, rationaliz...
3 grandmasters [grandmasters, grandmaster]
4 rehearsing [rehearsing, practice]
答案 1 :(得分:1)
如果是这种情况
df['Keyword'].apply(lambda x : [x])+df['Synonyms']