Pandas 柱提取 - python

我有电影的数据集,并给列名演员。我想创建一个新的数据框,说约翰尼·德普(Johnny Depp)将他的电影放在日期集中的影片中。
另外还有一个类型列,其元素为**动作|冒险|幻想|科幻
**。我想从中提取前两个单词,即动作,冒险并将其存储在两个单独的列中。

words = movies.genres.apply(lambda x: x.str.split('|').str[1])

这是我为体裁编写的代码,但由于“ str”对象没有属性“ str”而出现错误

参考方案

这样行吗?

ll = [['Johnny Depp', 'a|b|c', 'Movie_1'],['Johnny Depp', 'a|d', 'Movie_2'],['Marlon Brando', 'f', 'Movie_3']]
movies = pd.DataFrame(ll,columns=['actors','genres','titles'])
print(movies)

# Get it as matrix of 0,1.
genre_df = movies.genres.str.get_dummies()
print(genre_df)

# Bonus: get a column containing list of first 2 genres.
genre_df['first_genre'] = pd.Series([''.join(genre_df.iloc[i,:][genre_df.iloc[i,:] == 1][0:1].index.tolist()) for i in range(len(genre_df))])
genre_df['second_genre'] = pd.Series([''.join(genre_df.iloc[i,:][genre_df.iloc[i,:] == 1][1:2].index.tolist()) for i in range(len(genre_df))])
genre_df['actors'] = movies['actors']
genre_df['titles'] = movies['titles']
print(genre_df)

# Get Depp movie info only.
depp_df = genre_df[genre_df['actors'] == 'Johnny Depp'][['first_genre', 'second_genre', 'titles']]
print(depp_df)

希望这是您想要的格式,我不太了解。

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

Python Pandas:在多列上建立布尔索引 - python

尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…

Python Pandas:选择索引范围 - python

datas = [['RAC1','CD0287',1.52], ['RAC1','CD0695',2.08], ['RAC1','ADN103-1',2.01], ['RAC3','CD0258',…

python pandas:按行对条件进行分组 - python

我有一个大的pandas数据框,试图从中形成一些行的对。我的df如下所示:object_id increment location event 0 1 d A 0 2 d B 0 3 z C 0 4 g A 0 5 g B 0 6 i C 1 1 k A 1 2 k B ... ... ... ... 对象ID描述特定的对象。增量是每次发生某事(跟踪订单)时…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…