繁体   English   中英

从现有数据框创建新列

[英]Create new column from existing Dataframe

我有一个数据框,并尝试根据以下条件从现有列创建一个新列。

由指定的列EVENT_TYPE组数据只能过滤,其中列具有价值列车的行并将其命名为X。 新列的值为X.sum / X.length

这是输入数据框

+-----+-------------+----------+--------------+------+
|   id|   event_type|  location|fault_severity|source|
+-----+-------------+----------+--------------+------+
| 6597|event_type 11|location 1|            -1|  test|
| 8011|event_type 15|location 1|             0| train|
| 2597|event_type 15|location 1|            -1|  test|
| 5022|event_type 15|location 1|            -1|  test|
| 5022|event_type 11|location 1|            -1|  test|
| 6852|event_type 11|location 1|            -1|  test|
| 6852|event_type 15|location 1|            -1|  test|
| 5611|event_type 15|location 1|            -1|  test|
|14838|event_type 15|location 1|            -1|  test|
|14838|event_type 11|location 1|            -1|  test|
| 2588|event_type 15|location 1|             0| train|
| 2588|event_type 11|location 1|             0| train|
+-----+-------------+----------+--------------+------+

我想要以下输出。

 +--------------+------------+-----------+
 |              | event_type | PercTrain |
 +--------------+------------+-----------+
 |event_type 11 |   7888     | 0.388945  |
 |event_type 35 |   6615     | 0.407105  |
 |event_type 34 |   5927     | 0.406783  |
 |event_type 15 |   4395     | 0.392264  |
 |event_type 20 |   1458     | 0.382030  |
 +--------------+------------+-----------+

我已经尝试过此代码,但这会引发错误

    EventSet.withColumn("z" , when($"source" === "train" , sum($"source") / length($"source"))).groupBy("fault_severity").count().show()

这里的EventSet是输入数据帧

提供所需输出的Python代码是

event_type_unq['PercTrain'] = event_type.pivot_table(values='source',index='event_type',aggfunc=lambda x: sum(x=='train')/float(len(x))) 

我想您想获得火车价值的百分比。 所以,这是我的代码,

val df2 = df.select($"event_type", $"source").groupBy($"event_type").pivot($"source").agg(count($"source")).withColumn("PercTrain", $"train" / ($"train" + $"test")).show

并给出如下结果:

+-------------+----+-----+------------------+
|   event_type|test|train|         PercTrain|
+-------------+----+-----+------------------+
|event_type 11|   4|    1|               0.2|
|event_type 15|   5|    2|0.2857142857142857|
+-------------+----+-----+------------------+

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM