大熊猫:基于具有多个值的其他列添加df列映射到相同的新列值

时间:2019-01-04 00:49:38

标签: python pandas

我有一个这样的数据框:

df1 = pd.DataFrame({'col1' : ['cat', 'cat', 'dog', 'green', 'blue']})

,我想要一个提供该类别的新列,如下所示:

dfoutput = pd.DataFrame({'col1' : ['cat', 'cat', 'dog', 'green', 'blue'],
                         'col2' : ['animal', 'animal', 'animal', 'color', 'color']})

我知道我可以使用.loc来低效率地做到这一点:

df1.loc[df1['col1'] == 'cat','col2'] = 'animal'
df1.loc[df1['col1'] == 'dog','col2'] = 'animal'

如何将catdog合并为animal?这不起作用:

df1.loc[df1['col1'] == 'cat' | df1['col1'] == 'dog','col2'] = 'animal'

2 个答案:

答案 0 :(得分:3)

构建您的<div> <video src="path/video.mp4"></video> <div>This div must be removed</div> <div>Controls</div> </div> <div> <video src="path/video.mp4"></video> <div>This div must be removed</div> <div>Controls</div> </div> <button onclick="removeDivs()">Remove divs</button>然后执行dict

map

答案 1 :(得分:1)

由于多个项目可能属于一个类别,因此建议您从字典映射类别开始:

@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
    Object[] temp = input.toArray();
    return (Stream<T>) IntStream.range(0, temp.length)
            .mapToObj(i -> temp[temp.length - i - 1]);
}

您可能会发现它更易于维护。 然后使用字典理解功能,然后按pd.Series.map来反转字典:

cat_item = {'animal': ['cat', 'dog'], 'color': ['green', 'blue']}

您也可以使用pd.Series.replace,但这通常是less efficient