【问题标题】:finding a string in pandas dataframe column and cell在熊猫数据框列和单元格中查找字符串
【发布时间】:2018-02-21 21:30:10
【问题描述】:

我有一个如下的数据框,我想找出Jan 列中的值出现在URL 列和URL 列的相应单元格中的次数。

我想创建 3 列 - found in cellfound in columndistinct finds 例如,当我们从Jan 列的第一个单元格中搜索值try 时,它应该在found in cell 中返回1,在'found in columnand 2 indistinct findsbecause the word was found in 2 rows when we search for valuewhyfrom the second cell of the columnJan@ 中返回2 987654333@found in celland 2 in 'found in column and 2 in distinct finds 因为这个词在 2 行中被发现

我知道如何在字符串中搜索。但是如何在单元格和列中进行搜索?

s="ea2017-104.pdf bb cc for why"
s.lower().count("why")#to find text within string

sales = [{'account': '3', 'Jan': 'try', 'Feb': '200 .jones', 'URL': 'ea2018-001.pdf try bbbbb why try'},
             {'account': '1',  'Jan': 'why', 'Feb': '210', 'URL': 'try '},
             {'account': '2',  'Jan': 'bbbbb',  'Feb': '90',  'URL': 'ea2017-104.pdf bb cc for why' }]
df = pd.DataFrame(sales)
df

df['column_find']=df['URL'].str.lower().count('why')

最终输出 将有 3 个附加列,如下所示

found_inCell    found_in_column           distinct_finds
2                3                   2
0                2                   2
0                1                   1

更新

当我尝试在空/np.nan 中的一个单元格中运行代码时出现错误

sales = [{'account': '3', 'Jan': np.nan, 'Feb': '200 .jones', 'URL': 'ea2018-001.pdf try bbbbb why try'},
             {'account': '1',  'Jan': 'try', 'Feb': '210', 'URL': 'try '},
             {'account': '2',  'Jan': 'bbbbb',  'Feb': '90',  'URL': 'ea2017-104.pdf bb cc for why' }]
df = pd.DataFrame(sales)
df

df['found_inCell'] = df.apply(lambda row: row['URL'].count(row['Jan']), axis=1)
df['found_in_column'] = df['Jan'].apply(lambda x: ''.join(df['URL'].tolist()).count(x))
df['distinct_finds'] = df['Jan'].apply(lambda x: sum(df['URL'].str.contains(x)))

【问题讨论】:

    标签: python pandas search text


    【解决方案1】:

    这是一种方法。

    df['found_inCell'] = df.apply(lambda row: row['URL'].count(row['Jan']), axis=1)
    df['found_in_column'] = df['Jan'].apply(lambda x: ''.join(df['URL'].tolist()).count(x))
    df['distinct_finds'] = df['Jan'].apply(lambda x: sum(df['URL'].str.contains(x)))
    
    #           Feb    Jan                           URL account  found_inCell  \
    # 0  200 .jones    try  ea2018-001.pdf try bbbbb why       3             1   
    # 1         210    why                          try        1             0   
    # 2          90  bbbbb  ea2017-104.pdf bb cc for why       2             0   
    
    #    found_in_column  distinct_finds  
    # 0                2               2  
    # 1                2               2  
    # 2                1               1  
    

    【讨论】:

    • 谢谢...它正在工作...让我做更多测试
    • 如果Jan 列中的单元格为空,我会收到错误'must be str, not NoneType'...如何修改apply 函数,以便在单元格中的值为空时跳过行?
    猜你喜欢
    • 1970-01-01
    • 2021-01-08
    • 2022-01-12
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    相关资源
    最近更新 更多