Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

python - appending to lists in column of dataframe

I have a column in a dataframe containing lists of strings as such:

id    colname
1     ['str1', 'str2', 'str3']
2     ['str3', 'str4']
3     ['str3']
4     ['str2', 'str5', 'str6']
..

The strings in the list have some overlap as you can see. I would like to append the lists in this column with a value, for example 'strX'. The end result should be:

id    colname
1     ['str1', 'str2', 'str3', 'strX']
2     ['str3', 'str4', 'strX']
3     ['str3', 'strX']
4     ['str2', 'str5', 'str6', 'strX']
..

What would be the proper way to achieve this? I have tried appending and adding, but these don't get me the desired result.

question from:https://stackoverflow.com/questions/65918660/appending-to-lists-in-column-of-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can add list in Series.map or Series.apply:

df['colname'] = df['colname'].map(lambda x: x + ['strX'])
#alternative
#df['colname'] = df['colname'].apply(lambda x: x + ['strX'])
#or in list comprehension
#df['colname'] = [x + ['strX']  for x in df['colname']]
print (df)
   id                   colname
0   1  [str1, str2, str3, strX]
1   2        [str3, str4, strX]
2   3              [str3, strX]
3   4  [str2, str5, str6, strX]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...