Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫从包含名称列表的列中获取最常用的名称_Python_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 熊猫从包含名称列表的列中获取最常用的名称

Python 熊猫从包含名称列表的列中获取最常用的名称,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我的数据帧是这样的 star_rating actors_list 0 9.3 [u'Tim Robbins', u'Morgan Freeman'] 1 9.2 [u'Marlon Brando', u'Al Pacino', u'James Caan'] 2 9.1 [u'Al Pacino', u'Robert De Niro'] 3 9.0 [u'Christian Bale', u'Heath Ledger'] 4 8.9

我的数据帧是这样的

star_rating  actors_list
0   9.3     [u'Tim Robbins', u'Morgan Freeman']
1   9.2     [u'Marlon Brando', u'Al Pacino', u'James Caan']
2   9.1     [u'Al Pacino', u'Robert De Niro']
3   9.0     [u'Christian Bale', u'Heath Ledger']
4   8.9     [u'John Travolta', u'Uma Thurman']
我想提取演员列表列中最常见的名字。我找到了这个密码。你有更好的建议吗?特别是对于大数据

import pandas as pd
df= pd.read_table (r'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv',sep=',')
df.actors_list.str.replace("(u\'|[\[\]]|\')",'').str.lower().str.split(',',expand=True).stack().value_counts()
()的预期输出


根据我的测试,在计数后进行正则表达式清理要快得多

from itertools import chain
import re

p = re.compile("""^u['"](.*)['"]$""")
ser = pd.Series(list(chain.from_iterable(
    x.title().split(', ') for x in df.actors_list.str[1:-1]))).value_counts()
ser.index = [p.sub(r"\1", x) for x in ser.index.tolist()]


ser.head()

Robert De Niro    18
Brad Pitt         14
Clint Eastwood    14
Tom Hanks         14
Al Pacino         13
dtype: int64

使用普通python总比依赖pandas要好,因为如果列表很大,它会消耗大量内存

如果列表的大小为1000,那么当您使用
expand=True
时,非1000长度的列表将具有Nan,这是对内存的浪费。试试这个

df = pd.concat([df]*1000) # For the sake of large df. 

%%timeit
df.actors_list.str.replace("(u\'|[\[\]]|\')",'').str.lower().str.split(',',expand=True).stack().value_counts()
10 loops, best of 3: 65.9 ms per loop

%%timeit     
df['actors_list'] = df['actors_list'].str.strip('[]').str.replace(', ',',').str.split(',')
10 loops, best of 3: 24.1 ms per loop

%%timeit
words = {}
for i in df['actors_list']:
    for w in i : 
        if w in words:
            words[w]+=1
        else:
            words[w]=1

100 loops, best of 3: 5.44 ms per loop

我将使用
ast
将列表转换为
list

import ast 
df.actors_list=df.actors_list.apply(ast.literal_eval)
pd.DataFrame(df.actors_list.tolist()).melt().value.value_counts()
根据我得到的图表

哪个

  • coldspeed的代码是wen2()
  • Dark的代码是wen4()
  • 我的代码是wen1()
  • W-B的代码是wen3()

提供预期的输出。使用for循环总比将繁重的工作交给熊猫本身要好。@coldspeed我不认为这是一个重复的测试。如果你有一个巨大的列表,那么
expand=True
将杀死你的系统。@Dark没有
expand=True
.stack()不工作也别忘了计时这部分:
df['actors_list'].str.strip('[]').str.replace('','','',',').str.split(','))
@Dark:I get
只能使用带有字符串值的.str访问器,它在pandas中使用np.object uuudtype
错误代码。也是执行代码的地方。jupyter notebook和Ipython不接受%%。@Rezaenergy删除
%%timeit
部分及其结果,只使用代码。由于数据类型建议为对象,您可以直接运行以
words={}
@Dark开头的代码,谢谢您,没有%timeit或%%timeit它可以工作,但我不知道何时添加%%timeit它会导致此错误
只能使用带字符串值的.str访问器,在pandas中使用np.object udtype
它显示错误
ValueError:格式错误的节点或字符串:['Tim Robbins','Morgan Freeman','Bob Gunton']
也许最好从集合导入计数器中删除
,并将
添加到
x.title().split(',')
import ast 
df.actors_list=df.actors_list.apply(ast.literal_eval)
pd.DataFrame(df.actors_list.tolist()).melt().value.value_counts()