python - 替换数据框中的重复列

标签 python apache-spark pyspark

我在 pyspark 中有一个数据框。该数据框有一些带有特殊字符的列。

cols = df.schema.names

cols
['abc test', 'test*abc', 'eng)test', 'abc_&test']

reps = ((' ', '_&'), ('(', '*_'), (')', '_*'), ('{', '#_'), ('}', '_#'), (';', '_##'), ('.', '_$'), (',', '_$$'), ('=', '_**'))

def col_rename(x):
    new_cols = reduce(lambda a, kv: a.replace(*kv), reps, x)

for i in cols:
    df = df.withColumnRenamed(i, col_rename(cols, i))
return df

现在我想看看替换列名称中的特殊字符后是否存在重复的列。 我们可以看到 new_cols abc_&test

中有重复的列

发生这种情况时,我想返回额外的 _ 下划线

我的 new_cols 应如下所示

['abc__&test', 'test*_abc', 'eng_*test', 'abc_&test']

如何才能实现我想要的目标?

最佳答案

首先,您需要更改列名称,如

中定义
reps = [(' ', '_&'), ('(', '*_'), (')', '_*'), ('{', '#_'), ('}', '_#'), (';', '_##'), ('.', '_$'), (',', '_$$'), ('=', '_**')]

这可以通过创建一个新列表来完成

replacedCols = []
for col in cols:
    for x in reps:
        col = col.replace(x[0], x[1])
    replacedCols.append(col)

Now I want to see if after replacing the special characters in the column names if there are any duplicate columns. I want to return extra _ underscore when this happens.

您可以通过检查 replacedCols 中的每个列名称来做到这一点。数组

checkCols = replacedCols[:]
for index, col in enumerate(replacedCols):
    checkCols[index] = ''
    replacedCols[index]
    if col in checkCols:
        replacedCols[index] = col.replace('_', '__')

这样你就完成了。最后一步是重命名

for index, col in enumerate(cols):
    df = df.withColumnRenamed(col, replacedCols[index])

df.show(truncate=False)

你应该有

+----------+--------+---------+---------+
|abc__&test|test*abc|eng_*test|abc_&test|
+----------+--------+---------+---------+

我希望这会有所帮助。快乐编码。

关于python - 替换数据框中的重复列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120835/

相关文章:

python - 有没有一种Python式的方法来迭代两个列表的差异?

Python 文件() 函数

apache-spark - Spark.table 与 sql() AccessControlException

pyspark:两个日期列之间的小时差异

python高效的子串搜索

r - 如何在 EMR 集群上使用 Spark-Submit 或 SparkR 运行 SparkR 脚本?

apache-spark - Spark : Prevent shuffle/exchange when joining two identically partitioned dataframes

apache-spark - 有没有办法根据pyspark中的索引对数据帧进行切片?

apache-spark - pyspark - 合并 2 列集合

python - 如何使用正则表达式从文本中查找特定单词并返回所有匹配项?