【发布时间】:2018-02-21 21:30:10
【问题描述】:
我有一个如下的数据框,我想找出Jan 列中的值出现在URL 列和URL 列的相应单元格中的次数。
我想创建 3 列 - found in cell 和 found in column 和 distinct 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)))
【问题讨论】: