【问题标题】:How to add column of strings to another string in python?如何将字符串列添加到python中的另一个字符串?
【发布时间】:2022-01-04 10:38:12
【问题描述】:

我有一个字符串text ="a,b,c"

我在这样的数据框中有一组关键字:

book=

  col1  col2
  1    car
  2    bike
  3    bus
  4    train`

我想要一个输出字符串,方法是在 col2 中添加所有这些单词,并在文本中的每个单词后加上 + 符号:

样本输出:

a+car+bike+bus+train
b+car+bike+bus+train
c+car+bike+bus+train
....

【问题讨论】:

    标签: python pandas string


    【解决方案1】:

    假设您期望一个列表作为输出,您想要的很容易通过itertools.product 实现:

    from itertools import product
    
    text = 'a,b,c'
    list(map('+'.join, product(text.split(','), [df['col2'].str.cat(sep='+')])))
    

    输出:

    ['a+car+bike+bus+train',
     'b+car+bike+bus+train',
     'c+car+bike+bus+train']
    

    【讨论】:

      【解决方案2】:

      这可能是一个有用且简单的解决方案:

      # the initail string.
      str = "a,b,c"
      
      # separate the str string by the comma.
      str_list = str.split(',')
      
      # Import pandas library
      import pandas as pd
      
      # initialize list of lists
      data = [[1, 'car'], [2, 'bike'], [3, 'bus'], [4, 'train']]
      
      # Create the pandas DataFrame
      df = pd.DataFrame(data, columns = ['index', 'item'])
      
      # iterate over the str_list
      for s in str_list:
          # iterate over the dataframe.
          for index, row in df.iterrows():
              s = s + '+' + row['item']
          print(s)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-13
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 2019-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多