| 你可能已经注意到apply方法比iterrows方法快得多。其性能可媲美与NumPy数组,但apply方法提供了更多的灵活性。你可以在此处阅读apply方法的文档。(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html) 2. Pandas.DataFrame.loc | Python数据处理的技巧 这是我最喜欢的Pandas库的技巧之一。我觉得对于处理数据任务的数据科学家来说,这是一个必须知道的方法(所以几乎每个人都是这样!) 大多数时候,我们只需要根据某些条件来更新数据集中特定列的某些值。Pandas.DataFrame.loc为我们提供了针对此类问题的优化的解决方案。 让我们使用loc函数解决一个问题。你可以在此处下载将要使用的数据集(https://drive.google.com/file/d/1VwXDA27zgx5jIq8C7NQW0A5rtE95e3XI/view?usp=sharing)。 # 导入库 import pandas as pd data = pd.read_csv('school.csv') data.head() 
  
 检查“City”变量的各个值的频数:  
 现在,假设我们只需要排名前5位的城市,并希望将其余城市替换为“Others”(其他)城市。因此,让我们这么写: # 将热门城市保存在列表中 top_cities = ['Brooklyn','Bronx','Manhattan','Jamaica','Long Island City'] # 使用loc更新目标 data.loc[(data.City.isin(top_cities) == False),'City'] = 'Others' # 各个城市的频数 data.City.value_counts() 
  
 Pandas来更新数据的值是非常容易的!这是解决此类数据处理任务的优化方法。 3.在Python中向量化你的函数 摆脱慢循环的另一种方法是对函数进行向量化处理。这意味着新创建的函数将应用于输入列表,并将返回结果数组。Python中的向量化可以加速计算 让我们在相同的Twitter Sentiment Analysis数据集对此进行验证。 ''' 优化方法:向量化函数 ''' # 导入库 import pandas as pd  import numpy as np import time import math data = pd.read_csv('train_E6oV3lV.csv') # 输出头部信息 print(data.head()) def word_count(x) :  return len(x.split()) # 使用Dataframe iterrows 计算词的个数 print('nnUsing Iterrowsnn') start_time = time.time() data_1 = data.copy() n_words = [] for i, row in data_1.iterrows():  n_words.append(word_count(row['tweet'])) data_1['n_words'] = n_words  print(data_1[['id','n_words']].head()) end_time = time.time() print('nTime taken to calculate No. of Words by iterrows :', (end_time-start_time),'seconds') # 使用向量化方法计算词的个数 print('nnUsing Function Vectorizationnn') start_time = time.time() data_2 = data.copy() # 向量化函数 vec_word_count = np.vectorize(word_count) n_words_2 = vec_word_count(data_2['tweet']) data_2['n_words'] = n_words_2 print(data_2[['id','n_words']].head()) end_time = time.time() print('nTime taken to calculate No. of Words by numpy array : ', (end_time-start_time),'seconds') 
 难以置信吧?对于上面的示例,向量化速度提高了80倍!这不仅有助于加速我们的代码,而且使其变得更整洁。 4. Python中的多进程 多进程是系统同时支持多个处理器的能力。 在这里,我们将流程分成多个任务,并且所有任务都独立运行。当我们处理大型数据集时,即使apply函数看起来也很慢。 因此,让我们看看如何利用Python中的多进程库加快处理速度。 (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |