【问题标题】:How to use a list of values to find the same values in a dataframe如何使用值列表在数据框中查找相同的值
【发布时间】:2020-04-07 22:51:37
【问题描述】:

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)

【问题讨论】:

标签: python pandas function helper


【解决方案1】:

使用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", "golden", "brown", "blue"] 

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2022-11-24
    • 2018-09-19
    • 1970-01-01
    • 2019-12-30
    • 2019-07-19
    相关资源
    最近更新 更多