【发布时间】:2018-05-26 05:50:51
【问题描述】:
为特征工程目的实现以下逻辑。一个简单的方法很容易,但想知道是否有任何人都能想到的更有效的解决方案。如果您不想实现整个代码,我们将不胜感激!
获取这个 DataFrame 和字典
import pandas as pd
random_animals = pd.DataFrame(
{'description':['xdogx','xcatx','xhamsterx','xdogx'
,'xhorsex','xdonkeyx','xcatx']
})
cat_dict = {'category_a':['dog','cat']
,'category_b':['horse','donkey']}
我们想为字典中的每个字符串和每个类别创建一个列/特征。如果字符串包含在 description 列中,则为 1,否则为 0。
所以这个玩具示例的输出如下所示:
description is_dog is_cat is_horse is_donkey is_category_a is_category_b
0 xdogx 1 0 0 0 1 0
1 xcatx 0 1 0 0 1 0
2 xhamsterx 0 0 0 0 0 0
3 xdogx 1 0 0 0 1 0
4 xhorsex 0 0 1 0 0 1
5 xdonkeyx 0 0 0 1 0 1
6 xcatx 0 1 0 0 1 0
简单的方法是为每个需要和运行的输出列迭代一次(为了简单起见,对于每个列,这里只是硬编码 is_dog)
random_animals['is_dog'] = random_animals['description'].str.contains('dog')*1
cat_dict 中可以有任意数量的字符串和类别,所以我想知道是否有其他方法可以做到这一点。
【问题讨论】:
-
并非如此,如上例所示,我们希望添加 0/1 的整列,而不仅仅是关键字的计数。
-
如果您只想测试
category_a或category_b,可以使用快捷方式。如前所述,对于您的问题,我认为您无法比pd.Series.str.contains优化更多(在pandas技术范围内)。
标签: python pandas dummy-variable