【问题标题】:Merging dataframes合并数据框
【发布时间】:2018-05-28 16:14:58
【问题描述】:

我整天都在为这个问题苦苦挣扎。我有两个数据框如下:

数据框 1 - 广告牌

数据框 2

我想根据歌曲将 Dataframe 2 与 Dataframe 1 合并,最终得到一个包含 SongId、Song、Rank 和 Year 的数据框。问题是乐曲的存储方式存在一些变化。例如:Billboard 中的歌曲可以是 macarena bayside boy mix,而 Dataframe 2 中的歌曲可能是 macarena。我想找到相似之处。

【问题讨论】:

  • 将数据帧发布为文本而不是图像

标签: python pandas dataframe difflib


【解决方案1】:

我认为您需要计算 df1 和 df2 中歌曲列表之间的相似性度量。我通过在随机生成的歌曲列表中计算 df1 和 df2 中的歌曲之间的余弦距离来尝试一下。

from sklearn.feature_extraction.text import TfidfVectorizer
vect = TfidfVectorizer(min_df=1)

Song1 = ["macarena bayside boys mix", "cant you hear my heart beat", "crying in the chapell", "you were on my mind"]
Song2 = ["cause im a man", "macarena", "beat from my heart"]

dist_dict = {}
match_dict = {}
for i in Song1 :
    for j in Song2 :
        tfidf = vect.fit_transform([i, j])
        distance = ((tfidf * tfidf.T).A)[0,1]
        if i in dist_dict.keys():
            if dist_dict[i] < distance :
                dist_dict[i] = distance
                match_dict[i] = j
        else :
            dist_dict[i] = distance

找到最佳匹配后,您可以在 df2 中查找歌曲 ID

【讨论】:

    【解决方案2】:

    最简单的方法: 1. 将“Song”作为两个数据帧中的索引列,如

    df1.set_index('Song', inplace=True)
    df2.set_index('Song', inplace=True)
    
    1. 使用连接:

    joined = df1.join(df2, how='inner')

    【讨论】:

    • 查看OP的最后几句The problem is that there are some variations in how the Songs are stored. ex: Song in Billboard can be macarena bayside boys mix while Song in Dataframe 2 might be macarena. I wanted to find similarities.
    猜你喜欢
    • 2022-01-12
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2016-07-14
    相关资源
    最近更新 更多