如何删除dataframe中的列

时间:2017-07-22 20:37:19

标签: pyspark spark-dataframe

df2000.drop('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec').show()

enter image description here

现在它在数据框中显示没有删除的列

enter image description here

df2000.show()

当我单独运行show命令检查表时。但是附带了删除列。

1 个答案:

答案 0 :(得分:1)

drop不是副作用函数。它返回一个删除了指定列的新Dataframe。因此,您可以将新数据帧分配给稍后要引用的值,如下所示。

>>> df2000 = spark.createDataFrame([('a',10,20,30),('a',10,20,30),('a',10,20,30),('a',10,20,30)],['key', 'jan', 'feb', 'mar'])
>>> cols = ['jan', 'feb', 'mar']
>>> df2000.show()
+---+---+---+---+
|key|jan|feb|mar|
+---+---+---+---+
|  a| 10| 20| 30|
|  a| 10| 20| 30|
|  a| 10| 20| 30|
|  a| 10| 20| 30|
+---+---+---+---+

>>> cols = ['jan', 'feb', 'mar']
>>> df2000_dropped_col = reduce(lambda x,y: x.drop(y),cols,df2000)
>>> df2000_dropped_col.show()
+---+
|key|
+---+
|  a|
|  a|
|  a|
|  a|
+---+

现在对新数据框执行show将产生所需的结果,并删除所有月份列。