3

I have a Dataframe that contains the following values

    Keyword             Synonyms
0   fuzz                [hair, copper, pig, bull, cop, blur]
1   napkins             [table]
2   rationalizations    [systematization, rationalization]
3   grandmasters        [grandmaster]
4   rehearsing          [practice]

For the purpose of creating a dropdown menu in a later step, how would I append the value in the Keyword Column to the start of each list in the synonym column?

My code looks like this:

df['Synonyms'] = pd.concat([df['Keyword'].append(df['Synonyms'])
Learning Developer
  • 156
  • 2
  • 4
  • 14

2 Answers2

4

How about a list comprehension? In python3, you can use extended iterable unpacking to create a new list efficiently.

# 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]

Here's a fun alternative with 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]
cs95
  • 379,657
  • 97
  • 704
  • 746
1

If that is the case

df['Keyword'].apply(lambda x : [x])+df['Synonyms']
BENY
  • 317,841
  • 20
  • 164
  • 234