在python或Pyspark数据框中重命名具有特殊字符的列

时间:2017-03-12 21:44:13

标签: python pandas dataframe pyspark spark-dataframe

我在python / pyspark中有一个数据框。列具有特殊字符,如点(。)空格括号(())和括号{}。在他们的名字。

现在我想重命名列名,如果有点和空格,则用下划线替换它们,如果有()和{},则从列名中删除它们。

我已经完成了这个

df1 = df.toDF(*(re.sub(r'[\.\s]+', '_', c) for c in df.columns))

有了这个我能够用下划线替换点和空格而无法做第二位,即if()和{}只是从列名中删除它们。

我们如何实现这一目标。

2 个答案:

答案 0 :(得分:0)

Python 3.x解决方案:

tran_tab = str.maketrans({x:None for x in list('{()}')})

df1 = df.toDF(*(re.sub(r'[\.\s]+', '_', c).translate(tran_tab) for c in df.columns))

Python 2.x解决方案:

df1 = df.toDF(*(re.sub(r'[\.\s]+', '_', c).translate(None, '(){}') for c in df.columns))

答案 1 :(得分:0)

如果您有pyspark数据帧,可以尝试使用withColumnRenamed函数重命名列。我确实以我的方式尝试,看看并根据您的更改进行自定义。

>>> l=[('some value1','some value2','some value 3'),('some value4','some value5','some value 6')]
>>> l_schema = StructType([StructField("col1.some valwith(in)and{around}",StringType(),True),StructField("col2.some valwith()and{}",StringType(),True),StructField("col3 some()valwith.and{}",StringType(),True)])
>>> reps=('.','_'),(' ','_'),('(',''),(')',''),('{','')('}','')
>>> rdd = sc.parallelize(l)
>>> df = sqlContext.createDataFrame(rdd,l_schema)
>>> df.printSchema()
root
 |-- col1.some valwith(in)and{around}: string (nullable = true)
 |-- col2.some valwith()and{}: string (nullable = true)
 |-- col3 some()valwith.and{}: string (nullable = true)

>>> df.show()
+------------------------+------------------------+------------------------+
|col1.some valwith(in)and{around}|col2.some valwith()and{}|col3 some()valwith.and{}|
+------------------------+------------------------+------------------------+
|             some value1|             some value2|            some value 3|
|             some value4|             some value5|            some value 6|
+------------------------+------------------------+------------------------+

>>> def colrename(x):
...    return reduce(lambda a,kv : a.replace(*kv),reps,x)
>>> for i in df.schema.names:
...    df = df.withColumnRenamed(i,colrename(i))
>>> df.printSchema()
root
 |-- col1_some_valwithinandaround: string (nullable = true)
 |-- col2_some_valwithand: string (nullable = true)
 |-- col3_somevalwith_and: string (nullable = true)

>>> df.show()
+--------------------+--------------------+--------------------+
|col1_some_valwithinandaround|col2_some_valwithand|col3_somevalwith_and|
+--------------------+--------------------+--------------------+
|                 some value1|         some value2|        some value 3|
|                 some value4|         some value5|        some value 6|
+--------------------+--------------------+--------------------+