pyspark - 删除空列的快速方法 [PySpark]
问题描述
有没有一种简单的方法可以在 pyspark 中删除巨大数据集(300+ col >100k 行)的空列?比如df.dropna(axis=1,how='all')
在 Python 中
解决方案
是的,您可以简单地使用此处的答案。我threshold
给它添加了一个参数:
import pyspark.sql.functions as F
# Sample data
df = pd.DataFrame({'x1': ['a', '1', '2'],
'x2': ['b', None, '2'],
'x3': ['c', '0', '3'] })
df = sqlContext.createDataFrame(df)
df.show()
def drop_null_columns(df, threshold=0):
"""
This function drops all columns which contain null values.
:param df: A PySpark DataFrame
"""
null_counts = df.select([F.count(F.when(F.col(c).isNull(), c)).alias(c) for c in df.columns]).collect()[0].asDict()
to_drop = [k for k, v in null_counts.items() if v > threshold]
df = df.drop(*to_drop)
return df
# Drops column b2, because it contains null values
drop_null_columns(df).show()
输出
+---+---+
| x1| x3|
+---+---+
| a| c|
| 1| 0|
| 2| 3|
+---+---+
列 x2 已被删除。
您可以在使用threshold=df.count()
时使用它
推荐阅读
- javascript - 如何在图像的右上角叠加一个图标?
- javascript - 事件侦听器的切换案例有时会重新触发事件
- css - css没有水平滚动
- html - 如何在 HTML 代码中呈现求和符号?
- javascript - firebaseAuth.onAuthStateChanged 返回用户 null
- xml - XSD 1.1:属性与其他属性具有相同的值
- python - Web使用python从同一网站抓取页面列表
- java - 当我尝试获取字符串的字节但从字符到字节的转换溢出整数长度时会发生什么?
- python - Django:使用未找到参数“(”,)”的“删除”反向。尝试了 1 种模式:['$']
- python - pandas 中的 groupby 并从输出 DataFrame 中排除 grouper 列