sql - pyspark 中特定列的每个值始终为 NULL 的列类别
问题描述
我有一个非常大的表,我的数据库是 spark。假设它是这样的:
+----------------------------------------------------------------------------+
| col1 | col2 | col3 | col4(event_type) | col5 | col6 | ... |col20 |
+----------------------------------------------------------------------------+
| null | val1 | val2 | 'A' | val3 | null | ... | null |
| val4 | null | val5 | 'B' | val6 | null | ... | null |
| null | null | val7 | 'C' | null | val8 | ... | val9 |
| null | val1 | vall8 | 'A' | val2 | null | ... | null |
|............................................................................|
+-----------------------------------------------------------------------------
在这张表中,我们有很多列有很多 NULL 值。该表也有一列是type。对于每个类型值,某些列永远为空。例如在上表中,对于 type='A' col1 和 col5 和 col20 为 NULL。
我想为每种类型提取所有不为空的列名。(例如,对于“A”类型,我想获取 col1、col5 和 col20 名称)。
谁能帮我怎么做?
更新:
正如@Mohammad 所说,我尝试了这个 pyspark 代码:
from pyspark.sql import functions as F
df.groupBy("event_type").agg\
(F.first(F.concat_ws(",",*[(F.when(F.col(x).isNotNull(), F.lit(x)))\
for x in df.columns if x!='event_type'])).alias("non_null_columns")).show()
它似乎是正确的,但结果显示不正确。结果是这样的:
+--------------------+-----------------------------------------+
| event_type |all_not_null_columns_for_each_event |
+--------------------+-----------------------------------------+
| event1_name | timestamp,created...|
| event2_comple...| timestamp,created...|
| event3_name | timestamp,battery...|
| event5_name | timestamp,battery...|
| event6_name | timestamp,battery...|
| event7_comple...| timestamp,created...|
+--------------------+-----------------------------------------+
如您所见,结果并未完全显示,相反,我们看到...
解决方案
您可以使用 来实现通过列的循环Pyspark DataFrame API
,这是不可能的pure SQL.
df.show() #sampledata
#+----+----+----+----------+
#|col1|col2|col3|event_type|
#+----+----+----+----------+
#|null|val1|val2| A|
#|val4|null|val5| B|
#|null|null|val7| C|
#|null|val1|val8| A|
#+----+----+----+----------+
from pyspark.sql import functions as F
df.groupBy("event_type").agg\
(F.first(F.concat_ws(",",*[(F.when(F.col(x).isNotNull(), F.lit(x)))\
for x in df.columns if x!='event_type'])).alias("non_null_columns")).show()
#+----------+----------------+
#|event_type|non_null_columns|
#+----------+----------------+
#| B| col1,col3|
#| C| col3|
#| A| col2,col3|
#+----------+----------------+
推荐阅读
- html - HTML 电子邮件签名列向右浮动
- javascript - 数字字符串的二进制搜索数组未找到值
- r - Blogdown 和 hugo 不解析 Markdown 中的 html 标签
- drake - 对于多机器人仿真,我们是否需要多个多体植物?
- .htaccess - 在 RewriteCond 中没有扩展名的 REQUEST_FILENAME
- loops - BASIC:了解我自己的 Ada 代码。查找将整数除以无分数的数字
- c++ - C++中的指针向量
- markdown - 为什么我的 Rmarkdown ioslides 中不显示 ggplotly 函数
- react-native - 在 TabBottomNavigation React Native 上添加图标
- triggers - 更新触发器后用 null 替换空字符串将该列中的所有数据更新为 null