【问题标题】:Matching values of column within dataframe数据框中列的匹配值
【发布时间】:2019-05-07 20:24:34
【问题描述】:

我有一个如下所示的数据框:

Market         Price  date      outtime  intime  ttype
ATLJFKJFKATL   150    20190403  0215     0600    2
ATLJFK         77     20190403  0215     null    1
JFKATL         88     20190403  0600     null    1
JFKATL         77     20190403  0400     null    1

我想采用往返 (2) 的所有 ttypes (roundtrip = 2, one way = 1) 并将其与相应的一种方式相匹配,然后添加两列与每种方式的价格。我该怎么做?

结果数据框:

Market         Price  date      outtime  intime  outbound  inbound
ATLJFKJFKATL   150    20190403  0215     0600    77        88

它也可能是这样的:

Market         Price  date      outtime  intime  inOutList
ATLJFKJFKATL   150    20190403  0215     0600    [77,88]

任何一种方式都有效。 有时不会有唯一的匹配方式,因此该值要么为空,要么为空。

【问题讨论】:

  • 有匹配的键吗?
  • @VamsiPrabhala 没有匹配的键,只是检查是否有两种单向往返方式。寻找出站往返[:6]的一种方式并找到入站往返[6:]

标签: apache-spark pyspark


【解决方案1】:

您需要参加两次单程往返。您的加入密钥是Market、date 和time。往返市场必须分成 6 个字符代码以匹配单程市场:

首先,让我们将数据帧分为单程和往返:

import pyspark.sql.functions as psf
single, roundtrip = [df.filter(psf.col('ttype') == i).drop('ttype') for i in [1, 2]]

要提取往返的出站和入境市场,我们只需使用substring:

roundtrip = roundtrip \
    .withColumn('outMarket', psf.substring('Market', 0, 6)) \
    .withColumn('inMarket', psf.substring('Market', 7, 6))

我们现在可以加入两次(出站和入站):

single = single \
    .drop('intime') \
    .withColumnRenamed('outtime', 'time') \
    .withColumnRenamed('Price', 'bound')
single.persist()

for bound in ['out', 'in']:
    roundtrip = roundtrip \
        .join(
            single.select([psf.col(c).alias(bound + c) for c in single.columns if c != 'date'] + ['date']), 
            on=[bound + c for c in ['Market', 'time']] + ['date'], how='left')

roundtrip.show()

        +--------+------+--------+---------+-------+------------+-----+--------+-------+
        |inMarket|intime|    date|outMarket|outtime|      Market|Price|outbound|inbound|
        +--------+------+--------+---------+-------+------------+-----+--------+-------+
        |  JFKATL|  0600|20190403|   ATLJFK|   0215|ATLJFKJFKATL|  150|      77|     88|
        +--------+------+--------+---------+-------+------------+-----+--------+-------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多