python-3.x - 组合 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
解决方案
感谢您的回复!他们受到赞赏。我最初问,“有没有更快的方法来做到这一点。” 因此,如果您有兴趣,看来 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)
干杯!
推荐阅读
- r - 根据 col.names 中的 row.names 和条件汇总行 - R
- java - Java参数化方法解释
- android - Android 应用程序在 Pie 上出现 Textview 错误,但在 Oreo 上运行良好
- sql - 将表 1 的列 1 中的值替换为使用表 2 中的行中的值
- data-migration - 使用 Cloudendure 工具迁移 NFS(数据存储磁盘)
- python - 如何用((condition1 AND condition2)OR(condition2 AND condition3))构造一个sqlalchemy过滤器?
- google-analytics - Google Analytics Embed API 是否支持新的 GA4 属性?
- ruby-on-rails - Rails-复选框未变为真
- django - 测试密码保护页面django
- php - 我不知道它是如何调用的,但我希望事件可以通过 php 或 laravel 中的非阻塞用户操作从后端执行