Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
pyspark:删除所有行中具有相同值的列_Pyspark - Fatal编程技术网

pyspark:删除所有行中具有相同值的列

pyspark:删除所有行中具有相同值的列,pyspark,Pyspark,相关问题: 所以我有一个pyspark数据框,我想删除所有行中所有值都相同的列,同时保持其他列不变 然而,上述问题的答案只针对熊猫。pyspark dataframe是否有解决方案 谢谢您可以对每列应用countDistinct()聚合函数,以获得每列不同值的计数。count=1的列表示所有行中只有1个值 # apply countDistinct on each column col_counts = df.agg(*(countDistinct(col(c)).alias(c) for c

相关问题:

所以我有一个pyspark数据框,我想删除所有行中所有值都相同的列,同时保持其他列不变

然而,上述问题的答案只针对熊猫。pyspark dataframe是否有解决方案


谢谢

您可以对每列应用
countDistinct()
聚合函数,以获得每列不同值的计数。count=1的列表示所有行中只有1个值

# apply countDistinct on each column
col_counts = df.agg(*(countDistinct(col(c)).alias(c) for c in df.columns)).collect()[0].asDict()

# select the cols with count=1 in an array
cols_to_drop = [col for col in df.columns if col_counts[col] == 1 ]

# drop the selected column
df.drop(*cols_to_drop).show()

您可以使用
approx\u count\u distinct
函数()来计算列中不同元素的数量。如果只有一个不同的列,则删除相应的列

创建数据帧

from pyspark.sql.functions import approx_count_distinct
myValues = [(1,2,2,0),(2,2,2,0),(3,2,2,0),(4,2,2,0),(3,1,2,0)]
df = sqlContext.createDataFrame(myValues,['value1','value2','value3','value4'])
df.show()
+------+------+------+------+
|value1|value2|value3|value4|
+------+------+------+------+
|     1|     2|     2|     0|
|     2|     2|     2|     0|
|     3|     2|     2|     0|
|     4|     2|     2|     0|
|     3|     1|     2|     0|
+------+------+------+------+
计算不同元素的数量并将其转换为字典。

count_distinct_df=df.select([approx_count_distinct(x).alias("{0}".format(x)) for x in df.columns])
count_distinct_df.show()
+------+------+------+------+
|value1|value2|value3|value4|
+------+------+------+------+
|     4|     2|     1|     1|
+------+------+------+------+
dict_of_columns = count_distinct_df.toPandas().to_dict(orient='list')
dict_of_columns
    {'value1': [4], 'value2': [2], 'value3': [1], 'value4': [1]}

#Storing those keys in the list which have just 1 distinct key.
distinct_columns=[k for k,v in dict_of_columns.items() if v == [1]]
distinct_columns
    ['value3', 'value4']
删除具有不同值的列

df=df.drop(*distinct_columns)
df.show()
+------+------+
|value1|value2|
+------+------+
|     1|     2|
|     2|     2|
|     3|     2|
|     4|     2|
|     3|     1|
+------+------+

我得到一个错误:TypeError:unshable类型:“Column”