Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

pandas - how to make data frame's list rows to string?

I have a dataframe each row is a list like this:

   word_count   id  token
    0       6   0   [customer, executive]
    1       6   0   [purchase]
    2       6   0   [purchase, agent]
    3       6   0   [housekeeping]
    4       6   0   [night, auditor, &, guest, reception, agent]

I wanna convert the list to string like this:

  word_count id token
0       6   0   customer executive
1       6   0   purchase
2       6   0   purchase agent
3       6   0   housekeeping
4       6   0   night auditor & guest reception agent

I did the following method but when I see de.head() nothing change:

for index, row in de.iterrows():
    row['token']=' '.join(str(e) for e in row['token'])
de.head()

and

for index, row in de.iterrows():
    row['token']=' '.join(row['token'])
de.head()

and

for index, row in de.iterrows():
    row['token']=' '.join(row['token']).replace(',' ,' ')
de.head()
question from:https://stackoverflow.com/questions/65850200/how-to-make-data-frames-list-rows-to-string

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

1 Reply

0 votes
by (71.8m points)

List comprehension:

df['token'] = [' '.join(x) for x in df['token']]

Or apply:

df['token'] = df['token'].apply(' '.join)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...