【问题标题】:Faster way of building string combinations (with separator) than using a for loop?构建字符串组合(带分隔符)比使用 for 循环更快的方法?
【发布时间】:2022-01-20 14:41:09
【问题描述】:

我正在处理一个相对较大的数据集(在 Python 和 Pandas 中),并且正在尝试将多个列的组合构建为字符串。

假设我有两个列表; xy,其中:x = ["sector_1", "sector_2", "sector_3", ...]y = [7, 19, 21, ...]

我一直在使用for 循环来构建组合,例如combined = ["sector_1--7", "sector_1--19", "sector_1--21", "sector_2--7", "sector_2--19", ...],此处的分隔符定义为--

我当前的代码如下所示:

sep = '--'
combined = np.empty(0, dtype='object')
for x_value in x:
    for y_value in y:
        combined = np.append(combined,  str(x_value) + sep + str(y_value))
combined = pd.DataFrame(combined)
combined = combined.iloc[:, 0].str.split(sep, expand=True)

上面的代码有效,但我只是想知道是否有更好的方法(也许在运行时更有效)。

【问题讨论】:

  • 在我看来这个问题更适合在Code Review Forum 中提出。 Code Review 是一个针对同行程序员代码审查的问答网站。在发布您的问题之前,请阅读有关如何在本网站上正确提问的相关指南。
  • 哎呀,抱歉,我不知道有专门的同行程序员代码审查论坛。感谢您指出这一点!
  • combined = ["--".join(map(str,s)) for s in itertools.product(x, y)]?
  • 这能回答你的问题吗? Permutations between two lists of unequal length

标签: python pandas dataframe numpy runtime


【解决方案1】:

试试这个:

import itertools as it
combined = [f'{a}--{b}' for a, b in it.product(x, y)]

输出:

>>> combined
['sector_1--7',
 'sector_1--19',
 'sector_1--21',
 'sector_1--Ellipsis',
 'sector_2--7',
 'sector_2--19',
 'sector_2--21',
 'sector_2--Ellipsis',
 'sector_3--7',
 'sector_3--19',
 'sector_3--21',
 'sector_3--Ellipsis',
 'Ellipsis--7',
 'Ellipsis--19',
 'Ellipsis--21',
 'Ellipsis--Ellipsis']

不过,您应该使用np.tilenp.repeat 的组合:

combined_df = pd.DataFrame({0: np.repeat(x, len(x)), 1: np.tile(y, len(x))})

输出:

>>> combined_df
           0         1
0   sector_1         7
1   sector_1        19
2   sector_1        21
3   sector_1  Ellipsis
4   sector_2         7
5   sector_2        19
6   sector_2        21
7   sector_2  Ellipsis
8   sector_3         7
9   sector_3        19
10  sector_3        21
11  sector_3  Ellipsis
12  Ellipsis         7
13  Ellipsis        19
14  Ellipsis        21
15  Ellipsis  Ellipsis

【讨论】:

  • 这真的很有效!将我的运行时间减少了近一半,感谢您的帮助:))
猜你喜欢
  • 2012-04-19
  • 2013-07-04
  • 2013-09-13
  • 2014-01-19
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
相关资源
最近更新 更多