【问题标题】:Map multiple columns from pandas dataframe to a dictionary and conditionally return a value to a new column将 pandas 数据框中的多列映射到字典,并有条件地将值返回到新列
【发布时间】:2022-01-08 01:52:00
【问题描述】:

我有一个包含多个列的 pandas 数据框和一个包含与列名对应的键的字典。我想根据字典值检查列值,并根据列值是否满足“大于或等于”条件返回“是”或“否”。

例子:

import pandas as pd
dfdict = {'col1': [1,2,3], 'col2':[2,3,4], 'col3': [3.2, 4.2, 7.7]}
checkdict = {'col1': 2, 'col2': 3, 'col3': 1.5}
df = pd.DataFrame(dfdict)

对于每一列,每一行,检查行值是否大于或等于字典中的值。对于该行,如果任何列满足条件,则对新创建的列返回“是”,否则返回“否”。

我尝试过的:

def checkcond(element):
    if not math.isnan(element):
        x = checkdict[element]
        return 1 if element >= x else 0
    else:
        pass

df['test'] = df.applymap(checkcond)

但这当然行不通,因为行值是提供给 checkcond 函数而不是列名和行。

我也试过了:

df['test'] = pd.np.where(df[['col1', 'col2', 'col3']].ge(0).any(1, skipna=True), 'Y', 'N')

但这只会为“ge”条件取一个值,而我想根据每一列的字典值检查行值。

任何建议将不胜感激!

【问题讨论】:

  • 一个地方有“大于或等于”,另一个地方有“大于”,所以我猜是第一个;)
  • 很好,已编辑!

标签: python pandas dataframe dictionary


【解决方案1】:

将您的字典转换为系列并执行简单的比较:

df.ge(pd.Series(checkdict)).replace({True: 'yes', False: 'no'})

输出:

  col1 col2 col3
0   no   no  yes
1   no   no  yes
2  yes  yes  yes

获取每行的聚合:

df['any'] = df.ge(pd.Series(checkdict)).any(1).map({True: 'yes', False: 'no'})

输出:

   col1  col2  col3  any
0     1     2   3.2  yes
1     2     3   4.2  yes
2     3     4   7.7  yes

【讨论】:

  • 对不起@Scott ;)
  • 这是一个超级优雅的解决方案,虽然问题在技术上大于,所以 df['any'] = df.gt(pd.Series(checkdict)).any(1).map( {True: 'yes', False: 'no'}) 是正确的。忽略,问题大于或等于,逻辑描述大于,所以你的解决方案是完美的。请注意,您可以使用 gt 作为替代方案!
  • @IainD 这是我对 OP 的评论,在 gt/ge 上有歧义,无论如何这是次要的 ;)
猜你喜欢
  • 2015-07-24
  • 1970-01-01
  • 2016-09-02
  • 2021-11-25
  • 2021-07-14
  • 2023-02-21
  • 2020-08-25
  • 2021-08-21
  • 1970-01-01
相关资源
最近更新 更多