[英]Is it possible in python to replace words in list after comparing the columns in pandas dataframe?
例如:我有一個列表和一個列,即,
words = ["Processing", "Rocketing", "Rocking", "Rocked", "Processed"]
root_word first_word second_word
0 Process Processing Processed
1 Rocket Rocketing Rockets
2 Rock Rocking Rocked
現在我想得到像
new_word = ["Process", "Rocket", "Rock"]
基本上我想比較最后兩列中的單詞列表,如果在第一列的行(即 root_word)中找到單詞,則將該行單詞附加到新列表中(即 new_word)。 那么可以在python中做嗎?
new_words = df[
df['first_word'].isin(words) | df['second_word'].isin(words)
]['root_word'].tolist()
只需使用.loc[]
和 or |
過濾條件為真的數據.loc[]
操作員
In[322]: df.loc[df.first_word.isin(words) | df.second_word.isin(words),'root_word'].tolist()
Out[322]: ['Process', 'Rocket', 'Rock']
您可以使用pd.DataFrame.isin
:
words = ["Processing", "Rocketing", "Rocking", "Rocked", "Processed"]
res = df.loc[df[['first_word', 'second_word']].isin(words).any(axis=1), 'root_word'].tolist()
# ['Process', 'Rocket', 'Rock']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.