简体   繁体   English

在 pandas dataframe 中连接多个字符串列

[英]Concatenating multiple string columns in pandas dataframe

I'm trying to join 4 columsn of a dataframe, each has a list of values which need to be joined together:我正在尝试加入 dataframe 的 4 列,每个列都有一个需要连接在一起的值列表:

The working code is as follows:工作代码如下:

def create_soup(x):
    return ' '.join(x['keywords']) + ' ' + ' '.join(x['cast']) + ' ' + x['director'] + ' ' + ' '.join(x['genres'])
df['soup'] = df.apply(create_soup, axis=1)

My main issue with understanding this code is that df.apply function works on a row of data here, why can I not use this same code with the complete dataframe in one go.我理解这段代码的主要问题是df.apply function 在这里处理一行数据,为什么我不能在一个 Z34D1F91FB2E514B8576FAB1A7A7A 中使用与完整的 dataframe 相同的代码。

Is there any method to directly do this without the apply function?有没有什么方法可以在没有应用 function 的情况下直接执行此操作?

The data is as follows:数据如下:

在此处输入图像描述

The final line contains the output of the first movie - cast + director + keywords + genres最后一行包含第一部电影的 output - 演员 + 导演 + 关键字 + 流派

Use Series.str.join :使用Series.str.join

df['soup'] = (df['keywords'].str.join(' ') + ' ' + 
              df['cast'].str.join(' ') + ' ' + 
              df['director'] + ' ' +
              df['genres'].str.join(' '))

Similar:相似的:

df['soup'] = ((df['keywords'] + df['cast']).str.join(' ') + ' ' + 
               df['director'] + ' ' +
               df['genres'].str.join(' '))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM