簡體   English   中英

檢查每個列值是否存在於另一個 dataframe 列中,其中另一個列值是列 header

[英]Check if each column values exist in another dataframe column where another column value is the column header

companies.xlsx

    company     To
1   amazon      hi@test.de
2   google      bye@test.com 
3   amazon      hi@tld.com
4   starbucks   hi@test.de
5   greyhound   bye@tuz.de

emails.xlsx

   hi@test.de   bye@test.com    hi@tld.com   ...
1  amazon       google          microsoft
2  starbucks    amazon          tesla
3  Grey Hound   greyhound       
4  ferrari

所以我有上面的 2 張 excel 表並閱讀了兩個 em:

file1 = pd.ExcelFile('data/companies.xlsx')
file2 = pd.ExcelFile('data/emails.xlsx')

df_companies = file1.parse('sheet1')
df_emails = file2.parse('sheet1')

我想要完成的是:

  1. 檢查 df_companies['To'] 是否是 df_emails 中的現有 header
  2. 如果 df_emails 中存在 header,請在該 header 的相應列中搜索 df_companies['company']
  3. 如果找到公司,則在df_companies中添加一列並填寫'1',如果沒有填寫'0'

例如:亞馬遜公司在 company.xlsx 中有 To email hi@test.de。 在 email.xlsx 中存在 header hi@test.de 並且在列中也找到了亞馬遜 - 所以它是“1”。

任何人都知道如何做到這一點?

這是一種方法。 df_emails轉換為字典,並將 map 轉換為df_companies 然后,將映射列與df_companies['company']進行比較。

df_companies['check'] = df_companies['To'].map(df_emails.to_dict(orient='list')).fillna('')
df_companies['check'] = df_companies.apply(lambda x: x['company'] in x['check'], axis=1).astype(int)

     company            To  check
1     amazon    hi@test.de      1
2     google  bye@test.com      1
3     amazon    hi@tld.com      0
4  starbucks    hi@test.de      1
5  greyhound    bye@tuz.de      0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM