Calculate residual amount in dataframe column












1















I have a "capacity" dataframe:



scala> sql("create table capacity (id String, capacity Int)");
scala> sql("insert into capacity values ('A', 50), ('B', 100)");
scala> sql("select * from capacity").show(false)

+---+--------+
|id |capacity|
+---+--------+
|A |50 |
|B |100 |
+---+--------+


I have another "used" dataframe with following information:



scala> sql ("create table used (id String, capacityId String, used Int)");
scala> sql ("insert into used values ('item1', 'A', 10), ('item2', 'A', 20), ('item3', 'A', 10), ('item4', 'B', 30), ('item5', 'B', 40), ('item6', 'B', 40)")
scala> sql("select * from used order by capacityId").show(false)

+-----+----------+----+
|id |capacityId|used|
+-----+----------+----+
|item1|A |10 |
|item3|A |10 |
|item2|A |20 |
|item6|B |40 |
|item4|B |30 |
|item5|B |40 |
+-----+----------+----+


Column "capacityId" of the "used" dataframe is foreign key to column "id" of the "capacity" dataframe.
I want to calculate the "capacityLeft" column which is residual amount at that point of time.



+-----+----------+----+--------------+
|id |capacityId|used| capacityLeft |
+-----+----------+----+--------------+
|item1|A |10 |40 | <- 50(capacity of 'A')-10
|item3|A |10 |30 | <- 40-10
|item2|A |20 |10 | <- 30-20
|item6|B |40 |60 | <- 100(capacity of 'B')-40
|item4|B |30 |30 | <- 60-30
|item5|B |40 |-10 | <- 30-40
+-----+----------+----+--------------+


In real senario, the "createdDate" column is used for ordering of "used" dataframe column.




Spark version: 2.2











share|improve this question





























    1















    I have a "capacity" dataframe:



    scala> sql("create table capacity (id String, capacity Int)");
    scala> sql("insert into capacity values ('A', 50), ('B', 100)");
    scala> sql("select * from capacity").show(false)

    +---+--------+
    |id |capacity|
    +---+--------+
    |A |50 |
    |B |100 |
    +---+--------+


    I have another "used" dataframe with following information:



    scala> sql ("create table used (id String, capacityId String, used Int)");
    scala> sql ("insert into used values ('item1', 'A', 10), ('item2', 'A', 20), ('item3', 'A', 10), ('item4', 'B', 30), ('item5', 'B', 40), ('item6', 'B', 40)")
    scala> sql("select * from used order by capacityId").show(false)

    +-----+----------+----+
    |id |capacityId|used|
    +-----+----------+----+
    |item1|A |10 |
    |item3|A |10 |
    |item2|A |20 |
    |item6|B |40 |
    |item4|B |30 |
    |item5|B |40 |
    +-----+----------+----+


    Column "capacityId" of the "used" dataframe is foreign key to column "id" of the "capacity" dataframe.
    I want to calculate the "capacityLeft" column which is residual amount at that point of time.



    +-----+----------+----+--------------+
    |id |capacityId|used| capacityLeft |
    +-----+----------+----+--------------+
    |item1|A |10 |40 | <- 50(capacity of 'A')-10
    |item3|A |10 |30 | <- 40-10
    |item2|A |20 |10 | <- 30-20
    |item6|B |40 |60 | <- 100(capacity of 'B')-40
    |item4|B |30 |30 | <- 60-30
    |item5|B |40 |-10 | <- 30-40
    +-----+----------+----+--------------+


    In real senario, the "createdDate" column is used for ordering of "used" dataframe column.




    Spark version: 2.2











    share|improve this question



























      1












      1








      1


      0






      I have a "capacity" dataframe:



      scala> sql("create table capacity (id String, capacity Int)");
      scala> sql("insert into capacity values ('A', 50), ('B', 100)");
      scala> sql("select * from capacity").show(false)

      +---+--------+
      |id |capacity|
      +---+--------+
      |A |50 |
      |B |100 |
      +---+--------+


      I have another "used" dataframe with following information:



      scala> sql ("create table used (id String, capacityId String, used Int)");
      scala> sql ("insert into used values ('item1', 'A', 10), ('item2', 'A', 20), ('item3', 'A', 10), ('item4', 'B', 30), ('item5', 'B', 40), ('item6', 'B', 40)")
      scala> sql("select * from used order by capacityId").show(false)

      +-----+----------+----+
      |id |capacityId|used|
      +-----+----------+----+
      |item1|A |10 |
      |item3|A |10 |
      |item2|A |20 |
      |item6|B |40 |
      |item4|B |30 |
      |item5|B |40 |
      +-----+----------+----+


      Column "capacityId" of the "used" dataframe is foreign key to column "id" of the "capacity" dataframe.
      I want to calculate the "capacityLeft" column which is residual amount at that point of time.



      +-----+----------+----+--------------+
      |id |capacityId|used| capacityLeft |
      +-----+----------+----+--------------+
      |item1|A |10 |40 | <- 50(capacity of 'A')-10
      |item3|A |10 |30 | <- 40-10
      |item2|A |20 |10 | <- 30-20
      |item6|B |40 |60 | <- 100(capacity of 'B')-40
      |item4|B |30 |30 | <- 60-30
      |item5|B |40 |-10 | <- 30-40
      +-----+----------+----+--------------+


      In real senario, the "createdDate" column is used for ordering of "used" dataframe column.




      Spark version: 2.2











      share|improve this question
















      I have a "capacity" dataframe:



      scala> sql("create table capacity (id String, capacity Int)");
      scala> sql("insert into capacity values ('A', 50), ('B', 100)");
      scala> sql("select * from capacity").show(false)

      +---+--------+
      |id |capacity|
      +---+--------+
      |A |50 |
      |B |100 |
      +---+--------+


      I have another "used" dataframe with following information:



      scala> sql ("create table used (id String, capacityId String, used Int)");
      scala> sql ("insert into used values ('item1', 'A', 10), ('item2', 'A', 20), ('item3', 'A', 10), ('item4', 'B', 30), ('item5', 'B', 40), ('item6', 'B', 40)")
      scala> sql("select * from used order by capacityId").show(false)

      +-----+----------+----+
      |id |capacityId|used|
      +-----+----------+----+
      |item1|A |10 |
      |item3|A |10 |
      |item2|A |20 |
      |item6|B |40 |
      |item4|B |30 |
      |item5|B |40 |
      +-----+----------+----+


      Column "capacityId" of the "used" dataframe is foreign key to column "id" of the "capacity" dataframe.
      I want to calculate the "capacityLeft" column which is residual amount at that point of time.



      +-----+----------+----+--------------+
      |id |capacityId|used| capacityLeft |
      +-----+----------+----+--------------+
      |item1|A |10 |40 | <- 50(capacity of 'A')-10
      |item3|A |10 |30 | <- 40-10
      |item2|A |20 |10 | <- 30-20
      |item6|B |40 |60 | <- 100(capacity of 'B')-40
      |item4|B |30 |30 | <- 60-30
      |item5|B |40 |-10 | <- 30-40
      +-----+----------+----+--------------+


      In real senario, the "createdDate" column is used for ordering of "used" dataframe column.




      Spark version: 2.2








      scala apache-spark dataframe apache-spark-sql hiveql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 9:30









      Shaido

      12.6k122742




      12.6k122742










      asked Nov 20 '18 at 8:44









      user811602user811602

      5371828




      5371828
























          1 Answer
          1






          active

          oldest

          votes


















          1














          This can be solved by using window functions in Spark. Note that for this to work there need to exist a column that keep track of the row order for each capacityId.



          Start by joining the two dataframes together:



          val df = used.join(capacity.withColumnRenamed("id", "capacityId"), Seq("capacityId"), "inner")


          Here the id in the capacity dataframe is renamed to match the id name in the used dataframe as to not keep a duplicate columns.



          Now create a window and calculate the cumsum of the used column. Take the value of the capacity and subtract the cumsum to get the remaining amount:



          val w = Window.partitionBy("capacityId").orderBy("createdDate")
          val df2 = df.withColumn("capacityLeft", $"capacity" - sum($"used").over(w))


          Resulting dataframe with example createdDate column:



          +----------+-----+----+-----------+--------+------------+
          |capacityId| id|used|createdDate|capacity|capacityLeft|
          +----------+-----+----+-----------+--------+------------+
          | B|item6| 40| 1| 100| 60|
          | B|item4| 30| 2| 100| 30|
          | B|item5| 40| 3| 100| -10|
          | A|item1| 10| 1| 50| 40|
          | A|item3| 10| 2| 50| 30|
          | A|item2| 20| 3| 50| 10|
          +----------+-----+----+-----------+--------+------------+


          Any unwanted columns can now be removed with drop.






          share|improve this answer



















          • 1





            Thanks. It is giving me desired output.

            – user811602
            Nov 20 '18 at 9:48











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389165%2fcalculate-residual-amount-in-dataframe-column%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          This can be solved by using window functions in Spark. Note that for this to work there need to exist a column that keep track of the row order for each capacityId.



          Start by joining the two dataframes together:



          val df = used.join(capacity.withColumnRenamed("id", "capacityId"), Seq("capacityId"), "inner")


          Here the id in the capacity dataframe is renamed to match the id name in the used dataframe as to not keep a duplicate columns.



          Now create a window and calculate the cumsum of the used column. Take the value of the capacity and subtract the cumsum to get the remaining amount:



          val w = Window.partitionBy("capacityId").orderBy("createdDate")
          val df2 = df.withColumn("capacityLeft", $"capacity" - sum($"used").over(w))


          Resulting dataframe with example createdDate column:



          +----------+-----+----+-----------+--------+------------+
          |capacityId| id|used|createdDate|capacity|capacityLeft|
          +----------+-----+----+-----------+--------+------------+
          | B|item6| 40| 1| 100| 60|
          | B|item4| 30| 2| 100| 30|
          | B|item5| 40| 3| 100| -10|
          | A|item1| 10| 1| 50| 40|
          | A|item3| 10| 2| 50| 30|
          | A|item2| 20| 3| 50| 10|
          +----------+-----+----+-----------+--------+------------+


          Any unwanted columns can now be removed with drop.






          share|improve this answer



















          • 1





            Thanks. It is giving me desired output.

            – user811602
            Nov 20 '18 at 9:48
















          1














          This can be solved by using window functions in Spark. Note that for this to work there need to exist a column that keep track of the row order for each capacityId.



          Start by joining the two dataframes together:



          val df = used.join(capacity.withColumnRenamed("id", "capacityId"), Seq("capacityId"), "inner")


          Here the id in the capacity dataframe is renamed to match the id name in the used dataframe as to not keep a duplicate columns.



          Now create a window and calculate the cumsum of the used column. Take the value of the capacity and subtract the cumsum to get the remaining amount:



          val w = Window.partitionBy("capacityId").orderBy("createdDate")
          val df2 = df.withColumn("capacityLeft", $"capacity" - sum($"used").over(w))


          Resulting dataframe with example createdDate column:



          +----------+-----+----+-----------+--------+------------+
          |capacityId| id|used|createdDate|capacity|capacityLeft|
          +----------+-----+----+-----------+--------+------------+
          | B|item6| 40| 1| 100| 60|
          | B|item4| 30| 2| 100| 30|
          | B|item5| 40| 3| 100| -10|
          | A|item1| 10| 1| 50| 40|
          | A|item3| 10| 2| 50| 30|
          | A|item2| 20| 3| 50| 10|
          +----------+-----+----+-----------+--------+------------+


          Any unwanted columns can now be removed with drop.






          share|improve this answer



















          • 1





            Thanks. It is giving me desired output.

            – user811602
            Nov 20 '18 at 9:48














          1












          1








          1







          This can be solved by using window functions in Spark. Note that for this to work there need to exist a column that keep track of the row order for each capacityId.



          Start by joining the two dataframes together:



          val df = used.join(capacity.withColumnRenamed("id", "capacityId"), Seq("capacityId"), "inner")


          Here the id in the capacity dataframe is renamed to match the id name in the used dataframe as to not keep a duplicate columns.



          Now create a window and calculate the cumsum of the used column. Take the value of the capacity and subtract the cumsum to get the remaining amount:



          val w = Window.partitionBy("capacityId").orderBy("createdDate")
          val df2 = df.withColumn("capacityLeft", $"capacity" - sum($"used").over(w))


          Resulting dataframe with example createdDate column:



          +----------+-----+----+-----------+--------+------------+
          |capacityId| id|used|createdDate|capacity|capacityLeft|
          +----------+-----+----+-----------+--------+------------+
          | B|item6| 40| 1| 100| 60|
          | B|item4| 30| 2| 100| 30|
          | B|item5| 40| 3| 100| -10|
          | A|item1| 10| 1| 50| 40|
          | A|item3| 10| 2| 50| 30|
          | A|item2| 20| 3| 50| 10|
          +----------+-----+----+-----------+--------+------------+


          Any unwanted columns can now be removed with drop.






          share|improve this answer













          This can be solved by using window functions in Spark. Note that for this to work there need to exist a column that keep track of the row order for each capacityId.



          Start by joining the two dataframes together:



          val df = used.join(capacity.withColumnRenamed("id", "capacityId"), Seq("capacityId"), "inner")


          Here the id in the capacity dataframe is renamed to match the id name in the used dataframe as to not keep a duplicate columns.



          Now create a window and calculate the cumsum of the used column. Take the value of the capacity and subtract the cumsum to get the remaining amount:



          val w = Window.partitionBy("capacityId").orderBy("createdDate")
          val df2 = df.withColumn("capacityLeft", $"capacity" - sum($"used").over(w))


          Resulting dataframe with example createdDate column:



          +----------+-----+----+-----------+--------+------------+
          |capacityId| id|used|createdDate|capacity|capacityLeft|
          +----------+-----+----+-----------+--------+------------+
          | B|item6| 40| 1| 100| 60|
          | B|item4| 30| 2| 100| 30|
          | B|item5| 40| 3| 100| -10|
          | A|item1| 10| 1| 50| 40|
          | A|item3| 10| 2| 50| 30|
          | A|item2| 20| 3| 50| 10|
          +----------+-----+----+-----------+--------+------------+


          Any unwanted columns can now be removed with drop.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 '18 at 9:29









          ShaidoShaido

          12.6k122742




          12.6k122742








          • 1





            Thanks. It is giving me desired output.

            – user811602
            Nov 20 '18 at 9:48














          • 1





            Thanks. It is giving me desired output.

            – user811602
            Nov 20 '18 at 9:48








          1




          1





          Thanks. It is giving me desired output.

          – user811602
          Nov 20 '18 at 9:48





          Thanks. It is giving me desired output.

          – user811602
          Nov 20 '18 at 9:48




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389165%2fcalculate-residual-amount-in-dataframe-column%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)