1

我想做非常简单的事情,但无法弄清楚如何在 Python/Spark(1.5)/Dataframe 中做到这一点(这对我来说是全新的)。

原始数据集:

code| ISO | country
1   | AFG | Afghanistan state
2   | BOL | Bolivia Plurinational State

新数据集:

code| ISO | country
1   | AFG | Afghanistan
2   | BOL | Bolivia

我想做这样的事情(在伪 Python 中?):

iso_to_country_dict = {'AFG': 'Afghanistan', 'BOL': 'Bolivia'}

def mapCountry(iso,country):
    if(iso_to_country_dict[iso] is not empty):
        return iso_to_country_dict[iso]
    return country

dfg = df.select(mapCountry(df['ISO'],df['country']))

为简单起见, mapCountry 可能如下所示:

def mapCountry(iso,country):
    if(iso=='AFG'):
        return 'Afghanistan'
    return country

但这是有错误的:ValueError: Cannot convert column into bool:

4

2 回答 2

1

好吧,我找到了解决方案,但不知道这是否是最干净的方法。还有其他想法吗?

iso_to_country_dict = {'BOL':'玻利维亚','HTI':'佛得角','COD':'刚果','PRK':'韩国','LAO':'老挝'}

def mapCountry(iso,country):
    if(iso in iso_to_country_dict):
        return iso_to_country_dict[iso]
    return country

mapCountry=udf(mapCountry)

dfg = df.select(df['iso'],mapCountry(df['iso'],df['country']).alias('country'),df['C2'],df['C3'],df['C4'],df['C5'])

注意:C1,C2,..C5 是所有其他列的名称

于 2016-09-06T05:19:15.113 回答
0

我想提供一种不同的方法;UDF 始终是一种选择,但它们在 IMO 中有些低效且繁琐。whenotherwise范式可以解决这个问题。首先,为了提高效率 - 用 DataFrame 表示字典:

df_iso = spark.createDataFrame([('bol', 'Bolivia'),
                                ('hti', 'Cape-Verde'),
                                ('fra', 'France')], ['iso', 'country'])

然后让我们考虑以下数据:

df_data = spark.createDataFrame(
    map(lambda x: (x, ),
    ['fra', 'esp', 'eng', 'usa', 'bol']), ['data'])

然后我们通过连接进行 ISO 查找:

df_data = df_data.join(df_iso, F.col('data') == F.col('iso'),
                       'left_outer')

result最后,我们根据匹配添加所需的列(我将其命名为):

df_data = df_data.select(
    F.col('data'),
    F.when(F.col('iso').isNull(), F.col('data'))
    .otherwise(F.col('country')).alias('result'))

结果将是:

+----+-------+
|data|    res|
+----+-------+
| esp|    esp|
| bol|Bolivia|
| eng|    eng|
| fra| France|
| usa|    usa|
+----+-------+
于 2017-11-14T15:28:58.457 回答