动态重命名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屋!
查看全文