如何使用值列表在数据框中查找相同的值

streamingHistory dateframe for reference我有一个Spotify数据的数据框和一个前50名最受欢迎的艺术家的列表。我想使用此列表来查找每个相应的艺术家,而无需通过数据框25次。

# Find most popular artists from 2019
topFifty = streamingHistory[streamingHistory["year"] == 2019]["artistName"].value_counts().index[:50]
topFifty = streamingHistory[streamingHistory["artistName"] in top2019]

这段代码给我一个类型错误

TypeError: 'Series' objects are mutable,thus they cannot be hashed

我现在有这个功能(可以正常工作),但是我很好奇是否有一种方法可以不应用辅助功能...

topFifty = streamingHistory[streamingHistory["year"] == 2019]["artistName"].value_counts().index[:25]


def findArtists(row):
    if (row["artistName"] in topFifty) & row["year"] == 2019:
        return row

df = streamingHistory.apply(findArtists,axis=1).dropna().reset_index(drop=True)
tmp741852 回答:如何使用值列表在数据框中查找相同的值

使用numpy where可以限制条件的选择:

示例:

import pandas as pd 
import numpy as np

df = pd.DataFrame({"A" : np.random.choice(["blue","red","green","yellow","purple","black","white","brown","golden","silver"],200),"year" : np.random.choice([2011,2012,2013,2018,2019],200)})

ref_list = ["silver","blue"] 

df["matches"] = np.where((df["A"].isin(ref_list)) & (df["year"] == 2019),1,0)

在您的情况下,ref_list是艺术家的名字,您可以检查流历史艺术家是否在该列表内。然后,您还要求年份为2019。只有满足这两个条件时,numpy where才会返回1

本文链接:https://www.f2er.com/2920132.html

大家都在问