【发布时间】:2022-01-20 14:41:09
【问题描述】:
我正在处理一个相对较大的数据集(在 Python 和 Pandas 中),并且正在尝试将多个列的组合构建为字符串。
假设我有两个列表; x 和 y,其中: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)]?
标签: python pandas dataframe numpy runtime