通过列表字典筛选数据帧

2024-10-01 04:50:25 发布

您现在位置:Python中文网/ 问答频道 /正文

Movie Dataframe

我有一个包含电影信息的数据框,我正在尝试过滤这些行,以便如果字典列表包含“name”==“specified genre”,它将显示包含该类型的电影

我试过使用列表理解

filter = ['Action']
expectedResult = [d for d in df if d['name'] in filter]

但是,我最终出现了一个错误:

TypeError:字符串索引必须是整数


Tags: 数据namein信息类型dataframe列表字典
2条回答

您的循环for d in df将为您的值提供标题。 您的d将具有泛型作为值。 尝试运行:-

for d in df:
    print(d)

你会明白的

d是代码中的列名。这就是为什么会出现这个错误

请参见以下示例:

import pandas as pd

df = pd.DataFrame({"abc": [1,2,3], "def": [4,5,6]})
for d in df:
    print(d)

给出:

abc
def

我认为你要做的事情可以通过以下方式实现:

df = pd.DataFrame({"genre": ["something", "soemthing else"], "abc": ["movie1", "movie2"]})

movies = df.to_dict("records")

[m["abc"] for m in movies if m["genre"] == "something"]

其中:

['movie1']

相关问题 更多 >