1 python-3.x apache-spark apache-spark-sql pyspark
我有一个包含 432 列的数据框,并且有 24 个重复列。
我想删除 df_tickets 中重复的列。所以 df_tickets 应该只有 432-24=408 列。
我已经用下面的代码尝试过,但它抛出错误。
df_tickets.select([c for c in df_tickets.columns if c not in duplicatecols]).show()
Run Code Online (Sandbox Code Playgroud)
错误是
An error occurred while calling o1657.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
HashAggregate(keys=[ms_bvoip_order_extension_id#953, ms_order_id#954...........
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决这个问题吗?
您可能必须重命名一些重复的列才能过滤重复的列。否则,duplicatecols 中的列将全部被取消选择,而您可能希望为每一列保留一列。以下是一种可能有帮助的方法:
# an example dataframe
cols = list('abcaded')
df_ticket = spark.createDataFrame([tuple(i for i in range(len(cols)))], cols)
>>> df_ticket.show()
#+---+---+---+---+---+---+---+
#| a| b| c| a| d| e| d|
#+---+---+---+---+---+---+---+
#| 0| 1| 2| 3| 4| 5| 6|
#+---+---+---+---+---+---+---+
# unless you just want to filter a subset of all duplicate columns
# this list is probably not useful
duplicatecols = list('ad')
# create cols_new so that seen columns will have a suffix '_dup'
cols_new = []
seen = set()
for c in df_ticket.columns:
cols_new.append('{}_dup'.format(c) if c in seen else c)
seen.add(c)
>>> cols_new
#['a', 'b', 'c', 'a_dup', 'd', 'e', 'd_dup']
Run Code Online (Sandbox Code Playgroud)
然后根据新的列名称过滤结果
>>> df_ticket.toDF(*cols_new).select(*[c for c in cols_new if not c.endswith('_dup')]).show()
#+---+---+---+---+---+
#| a| b| c| d| e|
#+---+---+---+---+---+
#| 0| 1| 2| 4| 5|
#+---+---+---+---+---+
Run Code Online (Sandbox Code Playgroud)
这将保留具有相同列名的第一列。如果你想保留最后一个,这应该是一个简单的解决方法。理想情况下,您应该在创建具有重复列名的数据框之前调整列名。
| 归档时间: |
|
| 查看次数: |
14505 次 |
| 最近记录: |