gpt4 book ai didi

python - 将列中的值附加到包含列表的另一列的开头

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:11 25 4
gpt4 key购买 nike

我有一个包含以下值的数据框

    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'])

最佳答案

列表推导式怎么样?在 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]

关于python - 将列中的值附加到包含列表的另一列的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55678432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com