python - 如何合并字符串 pandas df

标签 python pandas merge

我正在尝试在 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/

相关文章:

python - 类型错误 : unhashable type: 'list' | Porting Odoo v8 to Odoo 12

Python MySQL 和上下文管理器 : __exit__ Attribute error

python - 如何将数据框中的某些行替换为其他数据框中具有附加列的相应行

Python:用于快速全屏 jpg/png 显示的 OSX 库

python - 在python中按数字部分按升序对包含数字和字母的字符串列进行排序

python - Pandas :计算两个数据帧之间的总百分比差异

MySQL复杂合并两个具有不同日期格式的表

c - Mercurial 预 merge 钩子(Hook)

Github 忽略 pull 请求中的下游配置文件

python - range() 函数给我带来了麻烦