I have a string text ="a,b,c"
and i have set of keywords in a dataframe like this:
book=
col1 col2
1 car
2 bike
3 bus
4 train`
i want an output string by adding all of these words in the col2
with a
sign after each word in text:
Sample output:
a car bike bus train
b car bike bus train
c car bike bus train
....
CodePudding user response:
Assuming you expect a list as output, what you want is easily achievable with itertools.product
:
from itertools import product
text = 'a,b,c'
list(map(' '.join, product(text.split(','), [df['col2'].str.cat(sep=' ')])))
output:
['a car bike bus train',
'b car bike bus train',
'c car bike bus train']
CodePudding user response:
Here is maybe a helpfully and simple solution:
# 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)