【问题标题】:Replace consecutive repeated characters with one - Column-wise operation - `pandas.DataFrame`用一个替换连续的重复字符-按列操作-`pandas.DataFrame`
【发布时间】:2017-03-30 15:15:16
【问题描述】:

如何删除字符串中的重复字符,只留下其中一个。

例如:-

"Bertuggggg Mete" 

"Bertug Mete"

我刚刚读过这样的数据:

dataFrame = pd.read_excel("C:\\Users\\Bertug\\Desktop\\example.xlsx")

名称 0 贝图格米特

从 .xlsx 文件中读取输入。我已经尝试过拆分和剥离功能,但它们似乎无法按预期工作。

我该如何解决这个问题?

【问题讨论】:

标签: python pandas


【解决方案1】:

看看这个:

column_name 替换为您要应用替换的列名。

min_threshold_rep = 2
column_name = 'Name'
dataframe[column_name]= dataframe[column_name].str.replace(r'(\w)\1{%d,}'%(min_threshold_rep-1), r'\1')

注意:这会将每个min_threshold_rep 个连续字符替换为一个字符。

【讨论】:

  • 它正在工作,非常感谢。你能在这里解释一下吗 (r'(\w)\1*', r'\1')。你是怎么解决这个问题的:)
  • \1 表示此处字符串中找到的第一个组-(\w) 将多个连续实例替换为一个。
【解决方案2】:

python 代码:

if __name__ == '__main__':
    s = 'Bertuggggg Mete'
    if len(s) == 0:
        print('wrong!')
        exit()
    r = s[0]
    for c in s:
        if r[len(r) - 1] != c:
            r += c
    print(r)

java代码:

public class Test {

public static void main(String[] args) {
    String s = "Bertuggggg Mete";
    StringBuffer sb = new StringBuffer();
    for (int i = 0, j = s.length(); i < j; i++) {
        if (i == 0) {
            sb.append(s.charAt(0));
        }
        if (s.charAt(i) != sb.charAt(sb.length() - 1)) {
            sb.append(s.charAt(i));
        }
    }
    System.out.println(sb);
}

}

【讨论】:

  • 你刚刚给了一个 Python 问题的 java 解决方案:P
  • 所以,我想。现在您可以将此代码移动到要点中的某个位置以供将来参考并从此处删除:P
  • 使用 python 3.5 ?
猜你喜欢
  • 1970-01-01
  • 2021-06-26
  • 2016-03-08
  • 1970-01-01
  • 2022-01-01
  • 2015-03-27
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
相关资源
最近更新 更多