pandas-python数据框更新列

3

假设我有一个名为 BRANDS 的列表,其中包含品牌名称:

BRANDS = ['Samsung', 'Apple', 'Nike', .....]

Dataframe A的结构如下:

row     item_title      brand_name

1    |  Apple 6S      |  Apple
2    |  Nike BB Shoes |  na  <-- need to fill with Nike
3    |  Samsung TV    |  na  <--need fill with Samsung
4    | Used bike      |  na  <--No need to do anything because there is no brand_name in the title 
    ....

我想用Nike填充第2行的brand_name列,Samsung填充第3行,因为它们为空,并且item_title包含在品牌列表BRANDS中能找到的关键字。我该怎么做?

3个回答

3

向量化解决方案:

In [168]: x = df.item_title.str.split(expand=True)

In [169]: df['brand_name'] = \
              df['brand_name'].fillna(x[x.isin(BRANDS)]
                                         .ffill(axis=1)
                                         .bfill(axis=1)
                                         .iloc[:, 0])

In [170]: df
Out[170]:
   row     item_title brand_name
0    1       Apple 6S      Apple
1    2  Nike BB Shoes       Nike
2    3     Samsung TV    Samsung
3    4      Used bike        NaN

1
一种方法是使用apply()函数:
import pandas as pd
BRANDS = ['Samsung', 'Apple', 'Nike']

def get_brand_name(row):
    if ~pd.isnull(row['brand_name']):
        # don't do anything if brand_name is not null
        return row['brand_name']

    item_title = row['item_title']
    title_words = map(str.title, item_title.split())
    for tw in title_words:
        if tw in BRANDS:
            # return first 'match'
            return tw
    # default return None
    return None

df['brand_name'] = df.apply(lambda x: get_brand_name(x), axis=1)
print(df)
#   row     item_title brand_name
#0    1       Apple 6S      Apple
#1    2  Nike BB Shoes       Nike
#2    3     Samsung TV    Samsung
#3    4      Used bike       None

注意事项

  • 我使用str.title()将分词标题转换为标题大小写,因为这是您定义品牌的方式。
  • 如果您有很多品牌,建议使用set而不是list,因为查找速度会更快。但是,如果您关心顺序,则无法使用。

0

通过编写一个简单的函数,您可以实现您想要的结果。然后,您可以使用 .apply()lambda函数 来生成您想要的列。

def contains_any(s, arr):
    for item in arr:
        if item in s: return item
    return np.nan
df['brand_name'] = df['product'].apply(lambda x: match_substring(x, product_map))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接