繁体   English   中英

比较pandas数据框中的列后,是否可以在python中替换列表中的单词?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM