如果我有下表
|a | id | year|m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 2001 | 0 | 0 | 0 | ... | 0 |
|"hello"| 1 | 2015 | 0 | 0 | 0 | ... | 0 |
|"hello"| 2 | 2002 | 0 | 0 | 0 | ... | 0 |
|"hello"| 2 | 2015 | 0 | 0 | 0 | ... | 0 |
如何更改資料框以檢查每一行中的年份列并將上面的示例 m2001 和 m2015 更改為 1,并且由于兩者的 id 均為 1,新表將如下所示
|a | id |m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 0 | 1 | 0 | ... | 1 |
|"hello"| 2 | 0 | 0 | 1 | ... | 1 |
uj5u.com熱心網友回復:
new = df.select('a','id','year',*[when((size(F.array_distinct(F.array(F.lit(col('year').astype('string')), lit(x[1:])))))==1,1).otherwise(0).alias(x) for x in df.columns if x not in ['a','id','year']])
new.groupBy('a','id').agg(*[max(x).alias(x) for x in new.columns if x not in ['a','id','year']] ).show()
這個怎么運作
將列折疊成行并將它們與年份列值配對
df.select('a','id','year',*[F.array(F.lit(col('year').astype('string')), lit(x[1:])).alias(x) for x in df.columns if x not in ['a','id','year']])
在每列的陣列中查找不同的元素
df.select('a','id','year',*[F.array_distinct(F.array(F.lit(col('year').astype('string')), lit(x[1:]))).alias(x) for x in df.columns if x not in ['a','id','year']])
查找各個列中每個陣列的大小
df.select('a','id','year',*[size(F.array_distinct(F.array(F.lit(col('year').astype('string')), lit(x[1:])))).alias(x) for x in df.columns if x not in ['a','id','year']])
最后,大小不為1的地方,表示列值和年份不一致,所以設為0,否則為1
最后,groupby 在每一列中添加查找最大值
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/531084.html
下一篇:回圈兩個變數以創建多個年份列
