从Python中的数据框中提取String

问题描述 投票:0回答:1

我有一个包含“genres列”的数据框,它的结构如下:

0    [{"id": 28, "name": "Action"}, {"id": 12, "nam..."
1    [{"id": 12, "name": "Adventure"}, {"id": 14, "..."
2    [{"id": 28, "name": "Action"}, {"id": 12, "nam..."
3    [{"id": 28, "name": "Action"}, {"id": 80, "nam..."
4    [{"id": 28, "name": "Action"}, {"id": 12, "nam..."
Name: genres, dtype: object

我只是想提取像“动作”“冒险”等类型。

我使用了不同的方法,但都没有实现。

d2 = pd.read_csv(r"C:\Users\nxx\PycharmProjects\tmdb_5000_movies.csv")
d2=pd.DataFrame(d2)
d2["genres"] = re.search(" (.?)}",d2["genres"]).group(1,2)

执行上面的代码时,我得到以下错误。

Name: genres, dtype: object
    return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object

我试图将列转换为str,但它不起作用。

我也试过了。

x=["Action","Crime","Horror","Drama","Comedy","Romance","Thriller","Documentary","Family","Adventure","Animation" "Science Fiction","Mystery","Fantasy","War","History","Music"]


d2["genres"] = d2["genres"].apply(lambda x: ", ".join(x["Action"] for i in x)) print(d2["genres"]) 
d2["genres"] = d2["genres"].apply(lambda x: ", ".join(x["Action"] for i in x)) TypeError: string indices must be integers –
python data-cleaning
1个回答
0
投票

如果需要从列表中提取名称

使用:

d2 = pd.read_csv(r"C:\Users\nxx\PycharmProjects\tmdb_5000_movies.csv")
d2["genres"] = d2["genres"].apply(lambda x: ", ".join(i["name"] for i in x))
© www.soinside.com 2019 - 2024. All rights reserved.