合并两个 pandas 数据框并根据条件创建一个新的二进制列
Merge two pandas dataframe and create a new binary column based on condition
我有两个数据框 - 有影响力的医学期刊列表和来自更广泛列表期刊的文章列表。
journal_id journal_title
1 Journal 1
2 Journal 2
3 Journal 3
article_id journal_title article_title
1 Journal 1 Title 1
2 Journal 2 Title 2
3 Journal 18 Title 3
4 Journal 55 Title 4
我想合并两个数据框并在第二个数据框中创建一个包含文章标题的新列,该列将标记为二进制输出,其中文章是否来自有影响力的期刊(二进制输出)。
预期输出
article_id journal_title article_title influential
1 Journal 1 Title 1 1
2 Journal 2 Title 2 1
3 Journal 18 Title 3 0
4 Journal 55 Title 4 0
欣赏创意!
可以先设置为False,满足条件的再设置为true。
df2['influential']=0
df2['influential'][df2['Journal'].isin(df1['Journal'].values)]=1
你也可以试试这个
df2 = df2.merge(df1['journal_title'], how='left', on='journal_title', indicator=True) # merges & creates indicators for matches
df2['influential'] = df2['_merge'].apply(lambda x: 1 if x == 'both' else 0) # if matches (both) then 1 else 0 for (left_only & right_only)
df2.drop(['_merge'], axis=1, inplace=True) #drops the column
我有两个数据框 - 有影响力的医学期刊列表和来自更广泛列表期刊的文章列表。
journal_id journal_title
1 Journal 1
2 Journal 2
3 Journal 3
article_id journal_title article_title
1 Journal 1 Title 1
2 Journal 2 Title 2
3 Journal 18 Title 3
4 Journal 55 Title 4
我想合并两个数据框并在第二个数据框中创建一个包含文章标题的新列,该列将标记为二进制输出,其中文章是否来自有影响力的期刊(二进制输出)。
预期输出
article_id journal_title article_title influential
1 Journal 1 Title 1 1
2 Journal 2 Title 2 1
3 Journal 18 Title 3 0
4 Journal 55 Title 4 0
欣赏创意!
可以先设置为False,满足条件的再设置为true。
df2['influential']=0
df2['influential'][df2['Journal'].isin(df1['Journal'].values)]=1
你也可以试试这个
df2 = df2.merge(df1['journal_title'], how='left', on='journal_title', indicator=True) # merges & creates indicators for matches
df2['influential'] = df2['_merge'].apply(lambda x: 1 if x == 'both' else 0) # if matches (both) then 1 else 0 for (left_only & right_only)
df2.drop(['_merge'], axis=1, inplace=True) #drops the column