gpt4 book ai didi

python - 如何合并字符串 pandas df

转载 作者:行者123 更新时间:2023-12-01 01:44:40 25 4
gpt4 key购买 nike

我正在尝试在 pandas df合并特定的字符串。下面的 df 只是一个示例。我的 df 中的值会有所不同,但基本规则将适用。我基本上想合并所有,直到出现4个字母的字符串

虽然此 df 中的 4 字母字符串始终为 Excl,但我的 df 将包含许多 4 字母字符串

import pandas as pd

d = ({
'A' : ['Include','Inclu','Incl','Inc'],
'B' : ['Excl','de','ude','l'],
'C' : ['X','Excl','Excl','ude'],
'D' : ['','Y','ABC','Excl'],
})

df = pd.DataFrame(data=d)

输出:

         A     B     C     D
0 Include Excl X
1 Inclu de Excl Y
2 Incl ude Excl ABC
3 Inc l ude Excl

预期输出:

         A     B     C     D
0 Include Excl X
1 Include Excl Y
2 Include Excl ABC
3 Include Excl

因此,row 0 保持不变,因为 col B 有 4 个字母。 Row 1Col A,B 合并为 Col C 4 个字母。 Row 2 与上面相同。 第 3 行 合并 Col A,B,C,因为 Col D 有 4 个字母。

我尝试通过合并所有来手动执行此操作,然后返回并删除不需要的值。

df["Com"] = df["A"].map(str) + df["B"]  + df["C"] 

但是我必须手动检查每一行并删除不同长度的字母。

上面的df只是一个例子。主要的相似之处是我需要合并 4 个字母字符串之前的所有内容。

最佳答案

你可以做类似的事情

mask = (df.iloc[:, 1:].applymap(len) == 4).cumsum(1) == 0
df.A = df.A + df.iloc[:, 1:][mask].apply(lambda x: x.str.cat(), 1)
df.iloc[:, 1:] = df.iloc[:, 1:][~mask].fillna('')

关于python - 如何合并字符串 pandas df,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com