首页 > 解决方案 > 组合 2 个字符串的最快方法,将字符串从第二列交错到整个数据帧中的第一列

问题描述

我编写了一个函数(包含从堆栈溢出中清除的位和部分),它将逐行移动整个数据帧,将字符串从 col-x 交错到 col-y,用于所有行中的所有两列 x,y 对。

我有一个可行的解决方案。问题是大型数据帧运行缓慢。

有更快的方法吗?

我尝试了以下设置:

# Import modules
import pandas as pd
from itertools import chain, zip_longest

def interleave_strings(string1, string2):
    tuples = zip_longest(string1, string2, fillvalue='')
    string_list = [''.join(item) for item in tuples]
    return ''.join(string_list)

# Create the pandas DataFrame 
data = [['timy', 'toma', 'tama', 'tima', 'tomy', 'tome'], ['nicka', 'nacka', 'nucka', 'necka', 'nomy', 'nome'], ['julia', 'Julia', 'jalia', 'jilia', 'jomy', 'jome']] 
df = pd.DataFrame(data, columns = ['A', 'B', 'C', 'D', 'E', 'F']) 

df

这让我们...

    timy    toma    tama    tima    tomy    tome
    nicka   nacka   nucka   necka   nomy    nome
    julia   Julia   jalia   jilia   jomy    jome

这有效,但慢慢地......

# new_df

il_df = pd.DataFrame()
for i in range (int(len(df.columns)/2)):
    selection = df.iloc[:,2*i:2*i+2]
    L = []
    for j in range (len(df.index)):
        res = interleave_strings(selection.iloc[j,0], selection.iloc[j,1])

        L.append(res)
        S = pd.Series(L)
    #il_df = pd.concat(D, ignore_index=True)   
    il_df = il_df.append(S, ignore_index=True)

il_df.transpose()

正确的输出是:

    0           1           2
0   ttiommya    ttaimmaa    ttoommye
1   nniacckkaa  nnuecckkaa  nnoommye
2   jJuulliiaa  jjailliiaa  jjoommye

标签: python-3.xstringpandasmultiple-columnsinterleave

解决方案


感谢您的回复!他们受到赞赏。我最初问,“有没有更快的方法来做到这一点。” 因此,如果您有兴趣,看来 Erfan 的方法比我的方法快一半,而 Karthik 的方法比我的要慢一些。

以下是在 jupyterlab 中运行的 %%timeit 实际交错的结果。如果你有更大的数据框,那些 ms 会加起来。

Erfan   - 3.46 ms ± 150 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
greg    - 6.81 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Karthik - 10.6 ms ± 98.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

干杯!


推荐阅读