我有一個字串 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
....
uj5u.com熱心網友回復:
假設你期望一個串列作為輸出,你想要的很容易實作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']
uj5u.com熱心網友回復:
這可能是一個有用且簡單的解決方案:
# 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367100.html
