首页 > 解决方案 > 在数据框的子集中查找单词

问题描述

我有这个数据集:

   Word                         Date
   paper pen                    03/02/2020
   pen                          03/02/2020
   salt                         03/03/2020
   Batch traditional loaf       03/04/2020
   Hi-fibre                     03/08/2020
   The pen is on the table      03/11/2020
   I went to the gym            03/10/2020

及其子集

            Num   Date
03/02/2020  43    03/02/2020
03/03/2020  12    03/03/2020
03/16/2020  32    03/16/2020
03/08/2020  42    03/08/2020
03/10/2020  21    03/10/2020

我想创建一个Date在子集中循环的函数,以提取具有Word包含pen在原始数据集中的值的行。

要查找我使用的字符串:

df[df[['Date','Word']].apply(lambda x : x.str.contains('pen'))]

df原始数据集在哪里。但是我不知道如何在子集 ( sub) 中循环 Date 以获取包含penin 的行df

我的预期输出,在 df 中查找以下日期:

    03/02/2020
    03/03/2020  
    03/16/2020  
    03/08/2020
    03/10/2020

将会

   Word                         Date
   paper pen                    03/02/2020
   pen                          03/02/2020

标签: pythonpandas

解决方案


基于循环的解决方案dates是可能的,但不推荐。
但是,如果由于某些原因需要循环,请尝试:

数据框df

                      Word        Date
0                paper pen  03/02/2020
1                      pen  03/02/2020
2                     salt  03/03/2020
3   Batch traditional loaf  03/04/2020
4                 Hi-fibre  03/08/2020
5  The pen is on the table  03/11/2020
6        I went to the gym  03/10/2020

数据框dates

         date
0  03/02/2020
1  03/03/2020
2  03/16/2020
3  03/08/2020
4  03/10/2020

代码:

df_out = pd.DataFrame()
for d in dates.date:
    for w in df.loc[df.Date==d, 'Word'].values:
        if 'pen' in w:
            df_out = df_out.append(pd.DataFrame({'Word':w, 'Date':d}, index = [d]))

结果df_out.reset_index(drop=True)

        Word        Date
0  paper pen  03/02/2020
1        pen  03/02/2020

推荐阅读