【问题标题】:Function that takes n rows as input and returns column names if sum in column equals n如果列中的总和等于 n,则将 n 行作为输入并返回列名的函数
【发布时间】:2020-01-13 02:55:30
【问题描述】:

我有一个大的DataFrame,其结构如下:

import pandas as pd

df = pd.DataFrame({'name1': [1, 0, 1,1],
                   'name2': [0, 0, 0,1],
                   'name3': [1, 1, 1,1],
                   'namen': [0, 0, 0,0]},
                  index=['label1', 'label2', 'label3', 'labeln'])
>>> df
      name1 name2 name3 name4
label1  1     0     1      1
label2  0     0     0      1
label3  1     1     1      1
label4  0     0     0      0

我正在尝试构建一个函数,它以 n 行名称作为参数对所有列中的值求和,如果这些列的总和等于 n。

例如,使用 label1、label2 和 label3 作为输入,我想获得以下输出:

def common_terms(*nargs):
   the function...

>>> common_terms(label1, label2, label3)
(name4)

>>> common_terms(label1, label3)
(name1, name3)

我对在 Python 中构建函数知之甚少,但我的头脑确实停留在这一点上。你能帮我进步吗?

【问题讨论】:

  • 举例说明你想要的输出

标签: python pandas pandas-loc


【解决方案1】:

loc 过滤行并测试每列是否所有1,然后过滤index 中的Series

def common_terms(*nargs):
   i = df.loc[list(nargs)].all()
   return i.index[i].tolist()

print (common_terms('label1', 'label2', 'label3'))
['namen']

print (common_terms('label1','label3'))
['name1', 'namen']

【讨论】:

  • 正是我想要的,如此优雅和简短。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2022-10-12
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多