【发布时间】:2017-07-25 21:03:52
【问题描述】:
我有一个大约 160k 行 x 24 列的大型数据框。我还有一个长度为 26 的 pandas 系列,我想将它逐行添加到我的数据帧中,以制作一个 160k 行 x 50 列的最终数据帧,但我的代码非常慢。
特别是这很慢,但它有效:
final = df.apply(lambda x: x.append(my_series), axis=1)
这会产生正确的最终形状:
Out[49]: (163008, 50)
其中,df.shape 是 Out[48]: (163008, 24),my_series.shape 是 Out[47]: (26,)
此方法对于
更新:为以下解决方案添加了基准
使用%timeit 使用测试数据框和测试系列进行了一些测试,大小如下:
test_df.shape
Out[18]: (156108, 24)
test_series.shape
Out[20]: (26,)
数据框和系列都包含字符串、浮点数、整数、对象等的混合。
接受使用 Numpy 的解决方案:
%timeit test_df.join(pd.DataFrame(np.tile(test_series.values, len(test_df.index)).reshape(-1, len(attributes)), index=test_df.index, columns=test_series.index))
10 loops, best of 3: 220 ms per loop
使用分配:
我的测试系列一直收到ValueError: Length of values does not match length of index,但当我使用更简单的系列时,只要它有效,不知道这里发生了什么......
@Divakar 使用自定义函数
%timeit rowwise_concat_df_series(test_df, test_series)
1 loop, best of 3: 424 ms per loop
【问题讨论】:
-
我认为你应该在你的标签中添加 numpy 以获得一个非常好的 numpy 人来审查这个问题。
-
数据框中有什么?都是数字(数字)吗?
-
@Divakar 它是浮点数、整数(64 位和 8 位)、字符串、数据帧对象的混合体,而 Series 包含对象 dtypes
-
那么,您有没有机会在您的实际数据集上计时发布的解决方案?
-
@Divakar 道歉,我对优化其他东西太深入了,我忘记了基准测试。我会将其添加到我的待办事项列表中,并在今天发布结果。谢谢提醒。