简体   繁体   English

为pandas数据帧中的每一行组合多个列

[英]Combine multiple columns for each row in pandas dataframe

My question is similar to this one: Combine two columns of text in dataframe in pandas/python 我的问题类似于此问题: 在pandas / python中的数据框中合并两列文本

However, I want to combine multiple columns, some of which are text and some are non-text. 但是,我想组合多个列,其中一些是文本,一些是非文本。 Moreover, I would like to do it in a loop, row by row because I need to preprocess the resulting text 而且,我想在一个循环中逐行进行,因为我需要预处理生成的文本

I tried: 我试过了:

 for i in range(len(df)):
      text = df.loc[i, text_cols].apply(lambda x: ' '.join(str(x)))

text_cols is a parameter. text_cols是一个参数。

But it seems the result is not a text but an array of chars... 但是似乎结果不是文本而是一个字符数组。

Update : It seems the following solution works: 更新 :似乎以下解决方案有效:

  text = ''
  for col in text_cols:
    text += ' ' + str(df.loc[i,col])

I wonder if there is a more fancy solution for it. 我想知道是否有更实用的解决方案。

Use iterrows: 使用iterrows:

for index, row in df.iterrows():
    "Pre-process your data here"
    "To process particular row you can do this"
    row["column_name to process"]


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

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