微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Pandas匹配多个列并将匹配值作为单个新列

我有一个大约5列的数据框.我希望匹配的值可以出现在最后3列中的任何一列中.

Key   |  col1   |  col2  |  col3 |  col4
----------------------------------------
1        abc       21        22      23
2        cde       22        21      20
3        fgh       20        22      23
4        lmn       20        22      21

我在最后三列中的任何一列上过滤值21,如下所示:

df1 = df [(df [‘col2′] ==’21’)| (df [‘col3′] ==’21’)| (DF [ ‘COL4′] == ’21’)]

这给了我

Key   |  col1   |  col2  |  col3 |  col4
----------------------------------------
1        abc       21        22      23
2        cde       22        21      20
4        lmn       20        22      21

使用这个新的df1我想得到这个

Key   |  col1   |  newCol
-------------------------
1        abc       21      
2        cde       21      
4        lmn       21      

基本上任何匹配的列作为新列值.我如何使用熊猫这样做?我很感激帮助.所以我想可能是我应该过滤并同时将它映射到新列,但我不知道如何?

解决方法:

这是一种方式.

import pandas as pd, numpy as np

df = pd.DataFrame([[1, 'abc', 21, 22, 23],
                   [2, 'cde', 22, 21, 20],
                   [3, 'fgh', 20, 22, 23],
                   [4, 'lmn', 20, 22, 21]],
                  columns=['Key', 'col1', 'col2', 'col3', 'col4'])

df2 = df[np.logical_or.reduce([df[col] == 21 for col in ['col2', 'col3', 'col4']])]\
        .assign(newCol=21)\
        .drop(['col2', 'col3', 'col4'], 1)

#    Key col1  newCol
# 0    1  abc      21
# 1    2  cde      21
# 3    4  lmn      21

说明

>将整数存储为整数而不是字符串.
> np.logical_or.reduce应用你的|列表理解中的条件.
> assign使用过滤器值创建一个新列.
> drop删除不需要的列,axis = 1表示列.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐