разделение значения столбца путем сопоставления других значений столбцов в python

#python #pandas #re

#python #pandas #python-re

Вопрос:

У меня есть фрейм данных, который выглядит следующим образом

 dummy = [["new york is a cool city in usa but i like london","cool","new","like"]]

df_dummy = pd.DataFrame(dummy,columns=["text","a","b","c"])
  

Теперь я хочу разделить строку текстового столбца, где совпадают другие значения столбцов.

Я пробовал следующий код, но не могу выйти за рамки этого.

 idx_ = [0]

cols_dummy = df_dummy.columns.values
cols_dummy = np.delete(cols_dummy,idx_,axis=0)
t_text = df_dummy.text.values[0]
for i in cols_dummy:
    match_ = "(" df_dummy[i].values[0] ")"

    tmp = re.split(match_,t_text)

    for e in range (0,len(tmp)):
        print(match_, tmp)
  

Ожидаемый результат:
["new", "york is a", "cool", "city in usa but i", "like", "london"]

Ответ №1:

Не самый красивый, но выполняет свою работу. Надеюсь, это вдохновит вас на реализацию чего-то подобного / лучшего.

 
t = "new york is a cool city in usa but i like london"
words = ["cool", "new", "like"]


def get_indicies(s, words):
    indicies = []
    for word in words:
        start = s.index(word)
        end = start   len(word)

        idx_tupl = (start, end)
        indicies.append(idx_tupl)
    return sorted(indicies)


def compose(s, indicies):
    result = []
    ptr = 0  # start at beginning of string
    for idx in indicies:

        if idx[0] != ptr:
            result.append(s[ptr : idx[0]])

        result.append(s[idx[0] : idx[1]])

        ptr = idx[1]

    result.append(s[ptr:])
    return result


def split_by_word(s, words):
    indices = get_indicies(s, words)
    return compose(s, indices)


print(split_by_word(t, words))
# output (Notice the whitespace around some string here)
['new', ' york is a ', 'cool', ' city in usa but i ', 'like', ' london']

  

Комментарии:

1. Это решение сохраняет пробелы по обе стороны от интересующих слов… Вы всегда можете добавить a strip() для приведения в порядок. Возможно, вы можете apply использовать эту функцию для некоторых столбцов вашего фрейма данных!