【问题标题】:searching if anyone of word is present in the another column of a dataframe or in another data frame using python使用python搜索数据框的另一列或另一个数据框中是否存在任何单词
【发布时间】:2017-12-16 17:22:24
【问题描述】:

您好,我有两个如下所示的 DataFrame

 DF1

 Alpha   |  Numeric  |  Special

 and     |  1        |   @
 or      |  2        |   $
         |  3        |   &  
         |  4        |     
         |  5        |     

DF2 with single column

Content      |

boy or girl  |
school @ morn|

我想搜索 DF1 中的任何列是否有 DF2 的内容列中的任何关键字,并且输出应该在新的 DF 中

 output_DF

 output_column|
 Alpha        |
 Special      |

有人帮我解决这个问题

【问题讨论】:

    标签: python pandas dataframe data-analysis


    【解决方案1】:

    我有个方法不太好。

    df1 = pd.DataFrame([[['and', 'or'],['1', '2','3','4','5'],['@', '$','&']]],columns=['Alpha','Numeric','Special'])    
    print(df1)
           Alpha          Numeric    Special
    0  [and, or]  [1, 2, 3, 4, 5]  [@, $, &]
    
    df2 = pd.DataFrame([[['boy', 'or','girl']],[['school', '@','morn']]],columns=['Content'])    
    print(df2)
                 Content
    0    [boy, or, girl]
    1  [school, @, morn]
    

    首先,合并df2数据:

    df2list=[x for row in df2['Content'].tolist() for x in row]
    print(df2list)
    ['boy', 'or', 'girl', 'school', '@', 'morn']
    

    然后获取df1每一列的数据与df2list相交:

    containlistname = []
    for i in range(0,df1.shape[1]):
        columnsname = df1.columns[i]
        df1list=[x for row in df1[columnsname].tolist() for x in row]
        intersection = list(set(df1list).intersection(set(df2list)))
        if len(intersection)>0:
            containlistname.append(columnsname)
    output_DF = pd.DataFrame(containlistname,columns=['output_column'])
    

    最终打印:

    print(output_DF)
      output_column
    0         Alpha
    1       Special
    

    【讨论】:

    • 我在这一行 df1list=[x for row in df1[columnsname].tolist() for x in row] 得到“TypeError: 'float' object is not iterable” 我也不想结合df2数据,我们需要找到每一行的匹配(是否可以迭代每一行?)
    • 你得到的“TypeError: 'float' object is not iterable”是我这边的数字是字符串格式的。至于你后面提到的问题,我想你只能做for每行循环。抱歉,我没有很好的方法来帮助你。
    • 你指的是哪个数字??,我将数值列值更改为字符串值,但我仍然面临同样的错误
    • 我的意思是 1,2,3,4,5,你有漂浮物,我身边有弦
    • 我将值更改为“一”、“二”、“三”、“四”、“五”,但我仍然面临这个问题
    【解决方案2】:

    您可以对 df1 中的每一列应用Series.isin() 方法,然后返回出现任何事件的列名:

    import pandas as pd
    
    d = {'Alpha' :['and', 'or'],'Numeric':[1, 2,3,4,5],'Special':['@', '$','&']}
    df1 = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.iteritems() ]))
    
    df2 = pd.DataFrame({'Content' :['boy or girl','school @ morn']})    
    
    check = lambda r:[c for c in df1.columns if df1[c].dropna().isin(r).any()]
    df3 = pd.DataFrame({'output_column' : df2["Content"].str.split(' ').apply(check)})
    

    这会导致:

      output_column
    0       [Alpha]
    1     [Special]
    

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 2021-06-11
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多