【问题标题】:Looking for faster way to iterate over pandas dataframe寻找更快的方法来迭代熊猫数据框
【发布时间】:2018-03-07 10:53:14
【问题描述】:

我有一个名为 df_ratings 的 pandas 数据框,大约有一百万行和 3 列。

我想获取这个数据框中的数据,对其进行转换,然后将其放入一个名为 ratings_matrix 的 numpy 矩阵中

我编写了以下代码来实现这一点:

for i in range(df_ratings.shape[0]): #fill matrix with ratings. zero = unrated
    current_user = df_ratings.iloc[i, 0] - 1
    current_movie = rated_movies_dictionary[df_ratings.iloc[i, 1]]
    current_rating = df_ratings.iloc[i, 2]

    ratings_matrix[current_movie, current_user] = current_rating

它可以工作,但速度很慢。在 for 循环中迭代数据帧的每一行很慢。有没有更快的方法来做到这一点?

【问题讨论】:

  • 没有任何数据很难判断。但是你可以摆脱循环。

标签: python pandas dataframe


【解决方案1】:
cuser = df_ratings.iloc[:, 0].values - 1
cmvie = df_ratings.iloc[:, 1].map(rated_movies_dictionary).values
crate = df_ratings.iloc[:, 2].values
ratings_matrix[cmvie, cuser] = crate

回复评论

.values 是否添加了一些东西? ——马丁·法布雷

是的!在做很多事情时,使用 numpy 数组通常更高效。由于最终目标是进行切片分配,因此我想将所有内容放入 numpy 数组中。作为一个简单的演示,我运行timeit,同时使用 pandas 系列和该系列中的 numpy 数组进行切片。

%timeit np.arange(4)[pd.Series([1, 2, 3])]
%timeit np.arange(4)[pd.Series([1, 2, 3]).values]

111 µs ± 2.25 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
61.1 µs ± 2.7 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

【讨论】:

  • 非常感谢,速度快多了。我想我应该在地图上阅读更多内容。
  • .values 是否添加了什么?
  • 据我所见,它将它从 Series 类型转换为 numpy 数组类型。
猜你喜欢
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 2020-05-17
  • 2015-12-09
  • 2021-10-24
  • 2022-01-16
相关资源
最近更新 更多