动态重命名 PySpark DataFrame 中的多个列 [英] Dynamically rename multiple columns in PySpark DataFrame
本文介绍了动态重命名 PySpark DataFrame 中的多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 pyspark 中有一个数据框,它有 15 列.
I have a dataframe in pyspark which has 15 columns.
列名分别为id
、name
、emp.dno
、emp.sal
、state
, emp.city
, zip
.....
The column name are id
, name
, emp.dno
, emp.sal
, state
, emp.city
, zip
.....
现在我想将包含 '.'
的列名替换为 '_'
Now I want to replace the column names which have '.'
in them to '_'
喜欢 'emp.dno'
到 'emp_dno'
我想动态地做
如何在 pyspark 中实现这一点?
How can I achieve that in pyspark?
推荐答案
您可以使用类似于 这个来自@zero323 的出色解决方案:
df.toDF(*(c.replace('.', '_') for c in df.columns))
或者:
from pyspark.sql.functions import col
replacements = {c:c.replace('.','_') for c in df.columns if '.' in c}
df.select([col(c).alias(replacements.get(c, c)) for c in df.columns])
replacement
字典看起来像:
{'emp.city': 'emp_city', 'emp.dno': 'emp_dno', 'emp.sal': 'emp_sal'}
更新:
如果我的数据框列名中有空格,那么如何替换'.'
和带有 '_'
if I have dataframe with space in column names also how do replace both
'.'
and space with'_'
import re
df.toDF(*(re.sub(r'[.s]+', '_', c) for c in df.columns))
这篇关于动态重命名 PySpark DataFrame 中的多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文