我在 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)
block 引用>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/