跨大 pandas DataFrame包含地图str。 [英] map str.contains across pandas DataFrame

查看:66
本文介绍了跨大 pandas DataFrame包含地图str。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的入门者-我正在寻找创建字符串和相关值的字典映射。我有一个数据框,想创建一个新列,如果字符串匹配,它将列标记为x。

Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x.

df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ipad2', 'acer chromebook', 'acer chromebookx', 'mac air', 'mac pro', 'lenovo x4'],
              'price':range(10)})

例如,我想使用上面的 df 并创建一个新列 df ['company'] 并将其设置为字符串映射。

For Example I would like to take the above df and create a new column df['company'] and set it to a mapping of strings.

我正在考虑做类似

product_map = {'dell':'Dell Inc.',
               'apple':'Apple Inc.',
               'acer': 'Acer Inc.',
               'mac': 'Apple Inc.',
               'lenovo': 'Dell Inc.'}

然后我要遍历它以检查 df.comp 列,查看每个条目是否包含这些字符串之一,并进行设置将 df.company 列添加到字典中的值。

Then I wanted to iterate through it to check the df.comp column and see if each entry contained one of those strings, and to set the df.company column to the value in the dictionary.

虽然不确定如何正确执行此操作。

Not sure how to do this correctly though.

推荐答案

有很多方法可以做到这一点。一种方法是:

There are many ways to do this. One way to do it would be the following:

def like_function(x):
    group = "unknown"
    for key in product_map:
        if key in x:
            group = product_map[key]
            break
    return group

df['company'] = df.comp.apply(like_function)

这篇关于跨大 pandas DataFrame包含地图str。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆