将 pandas 数据框中的字符串拆分为 3 个(三元组)

我有一个像这样的 df:


col1

AAP CO. LTD.

AAS dds dTdD.

我正在尝试创建一个函数来生成 pandas df 列,就像col2它分割col1每 3 个(或 n 个)字符一样:


col1           col2

AAP CO. LTD.   ['AAP','AP ','P C','CO.','O. '...]

AAS dds dTdD.  ['AAS','AS ','S d','dds','ds '...]

我已经尝试过这段代码,但它只是为每一行重复相同的字符串列表......


def trigram(self):

    for b in df.parent_org_name:

        a = ["".join(j) for j in zip(*[b[i:] for i in range(3)])]

    #     [b[i:i+3] for i in range(len(b)-1)]

    return a

    #     print(a)

    

df.apply(trigram, axis=1)

有任何想法吗?


小怪兽爱吃肉
浏览 162回答 3
3回答

倚天杖

您可以添加更多逻辑,具体取决于如果您提供的N大于字符串长度的情况会发生什么(目前我在列表中返回原始字符串)。字符串切片,将切片开始和停止索引增加 1,并确保到达字符串末尾后停止,否则可能会返回长度 <N 的子字符串。import numpy as npdef split_str(s, N):&nbsp; &nbsp; rmax = np.clip(len(s)-N, a_min=0, a_max=None)+1&nbsp; &nbsp; return [s[0+i:N+i] for i in range(0, rmax)]df['col1'].apply(lambda x: split_str(x, 3))#0&nbsp; &nbsp; [AAP, AP , P C,&nbsp; CO, CO., O. , . L,&nbsp; LT, LTD, ...#1&nbsp; &nbsp; [AAS, AS , S d,&nbsp; dd, dds, ds , s d,&nbsp; dT, dTd, ...#Name: col1, dtype: object# To show actual valuesdf['col1'].apply(lambda x: split_str(x, 3))[0]#['AAP', 'AP ', 'P C', ' CO', 'CO.', 'O. ', '. L', ' LT', 'LTD', 'TD.']

繁花不似锦

我想这就是你所需要的:)。如果需要使用不同于 3 的参数 n 来运行它,那么他们可以相应地更改括号中的 i+3df["col2"] = df.apply(lambda x: [x[0][i:i+3] for i in range(0, len(x[0]))],axis=1)&nbsp;#The result looks as follows&nbsp; &nbsp;col1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; col20&nbsp; AAP CO. LTD.&nbsp; [AAP, AP , P C,&nbsp; CO, CO., O. , . L,&nbsp; LT, LTD, ...&nbsp;1&nbsp; AAS dds dTdD. [AAS, AS , S d,&nbsp; dd, dds, ds , s d,&nbsp; dT, dTd, ...&nbsp;

慕斯王

不要循环遍历所有行,而是更改函数定义,如下所示 -def trigram(self):&nbsp; &nbsp; b=self.col1&nbsp; &nbsp; a = ["".join(j) for j in zip(*[b[i:] for i in range(3)])]#&nbsp; &nbsp; &nbsp; &nbsp; a = ["".join(j) for j in zip(*[b[i:] for i in range(3)])]&nbsp; &nbsp; #&nbsp; &nbsp; &nbsp;[b[i:i+3] for i in range(len(b)-1)]&nbsp; &nbsp; return a
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python