【问题标题】:List comprehension with multiple conditions on different columns在不同列上具有多个条件的列表理解
【发布时间】:2022-01-23 17:20:56
【问题描述】:

我有以下df,

data = [['Male', 'Agree'], ['Male', 'Agree'], ['Male', 'Disagree'], ['Female','Neutral']]
 
df = pd.DataFrame(data, columns = ['Sex', 'Opinion'])
df

& 想获得同意或不同意的男性总数。我希望答案是 3,但结果却是 9。

sum([True for x in df['Opinion'] for y in df['Sex'] if x in ['Agree','Disagree'] if y=='Male' ] 

我已经通过其他方法做到了这一点,我正在尝试更好地理解列表理解。

【问题讨论】:

标签: python pandas list-comprehension


【解决方案1】:

让我们稍微解开一下。原话

total = sum([True for x in df['Opinion'] for y in df['Sex'] if x in ['Agree','Disagree'] if y=='Male' ]

等价于

total = 0
for x in df['Opinion']:
    for y in df['Sex']:
        if x in ['Agree', 'Disagree']:
            if y=='Male':
                total += 1

我认为在这种情况下应该清楚为什么你会得到9

您真正想要的是只考虑两个大小相等的可迭代对象的对应对。有方便的zip 内置在 python 中,可以做到这一点,

total = 0
for x,y in zip(df['Opinion'], df['Sex']):
    if x in ['Agree', 'Disagree'] and y=='Male':
        total += 1

或作为一种理解

total = sum(1 for x,y in zip(df['Opinion'], df['Sex']) if x in ['Agree', 'Disagree'] and y=='Male')

【讨论】:

  • 而且,你最后没有使用列表理解,对 :) 我认为 OP 注意到了,因为他们接受了所以我现在离开。
  • @Neither hehe,是的,我把它换成了一个生成器,因为我不能让自己推荐构建完整的列表,只是为了让它立即减少一个总和。认为在答案中添加该讨论可能会使事情变得混乱。
猜你喜欢
  • 1970-01-01
  • 2017-03-20
  • 2021-12-08
  • 2021-11-17
  • 2023-02-14
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多