【问题标题】:How to add all values across pandas columns when the names of these columns match those in a list?当这些列的名称与列表中的名称匹配时,如何跨熊猫列添加所有值?
【发布时间】:2019-04-19 03:10:55
【问题描述】:
list = ['abc', 'def_1', 'xyz_8']

下面是df 的示例行

abc_1     abc_99    def_1     def_2    xyz_8    xyz_1
2         1         1         2        2        3

我想根据列表仅扫描并选择部分df 列。列表元素可以是列名的子字符串。例如,列abc_1 将被包含,因为abc 是一个子字符串,但xyz_1 不包括在内,因为xyz_1 不是列表的元素,并且列表元素都不是xyz_1 的子字符串。

我想要该行的 df['sum'] = 6(或 2+1+1+2)。

【问题讨论】:

    标签: python string python-3.x pandas indexing


    【解决方案1】:

    filter / str.contains

    您可以使用filterstr.contains,两者都支持正则表达式:

    L = ['abc', 'def_1', 'xyz_8']
    
    # courtesy of @JonClements
    df['result'] = df.filter(regex='|'.join(L)).sum(1)
    
    # original
    df['result'] = df.iloc[:, df.columns.str.contains('|'.join(L))].sum(1)
    
    print(df)
    
       abc_1  abc_99  def_1  def_2  xyz_8  xyz_1  result
    0      2       1      1      2      2      3       6
    

    【讨论】:

    • 或者df['result'] = df.filter(regex='|'.join(L)).sum(1)
    • @JonClements,是的,这实际上更好,谢谢:) - 虽然我不确定这里哪个更快
    • 天真地,我希望过滤器总是返回一个视图,而 .iloc 可能会或可能不会返回一个副本(永远不记得什么必须复制和什么不复制的规则.. .(熊猫也没有——考虑到所有关于“你正在尝试......”的警告)......(现在有点太累了,无法真正研究它——这只是我最初的想法(而且很可能是错误的,但是哦,好吧))
    • 大部分都理解了这条线,但是 .sum() 中的“1”到底是什么意思?
    • @KubiK888, axis=1 表示跨列总和,as described in the docs
    猜你喜欢
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多