【问题标题】:Pandas dataframe apply function to the values of several rows as a listPandas 数据框将函数作为列表应用于多行的值
【发布时间】:2020-08-24 08:32:59
【问题描述】:

我的问题是基于这个:

Apply pandas function on column only on certain rows

但我需要一个函数,该函数适用于一列中多行的值,就好像这些值是一个列表一样。

例如,如果我选择类别 c1,我的函数应该像这样应用:f([3,5])


|   user  |       category    | val  | 
| ------  | ------------------| -----|
| user 1  | c1                |   3  |  
| user 1  | c2                |   4  |
| user 1  | c3                |   8  | 
| user 2  | c1                |   5  |
| user 2  | c2                |   9  | 
| user 2  | c3                |   10 |

【问题讨论】:

  • 你可以groupby然后申请,你想申请什么功能?
  • 我们需要更多信息。更新您想要的最终结果。您要使用哪些行?标准是什么?
  • 我想使用的行:category = c1.该函数应用于一个列表(val 列中的值)并检查列表中是否有任何重复项以及列表的大小是否小于 10。

标签: python pandas list function dataframe


【解决方案1】:

我创建了一个自定义函数,给定一个数据框,检查 val 中是否有任何重复,以及 val 的大小是否低于 10,在感兴趣的类别上

df = pd.DataFrame({'user':['user 1','user 1','user 1','user 2','user 2','user 2'],
                   'category':['c1','c2','c3','c1','c2','c3'],
                   'val':[3,4,8,5,9,10]})

def custom_func(df, category):

    partial_df = df[df.category==category].copy()
    if len(partial_df.val)<10 and partial_df.val.duplicated().sum()>0:
        return True
    else:
        return False

custom_func(df, 'c1')

【讨论】:

  • partial_df = df[df.category==category].copy() partial_df.val.duplicated().sum()>0:
  • df[df.category==category].copy() 是对感兴趣类别的过滤器,而 df.val.duplicated().sum()>0 是检查是否存在在感兴趣的列中重复
【解决方案2】:

根据@Marco Cerliani 的回答,我想我设法做到了。

数据框首先带有 filter_keywords 列。

这远非优雅……

urls = ['url1','url2']

def size_check(df, URL):
    partial_df = df[df.URL==URL].copy()
    if len(partial_df.filter_keywords)<10: 
        return True
    else:
        return False

# true there is a duplicate. false there is no duplicate
def duplicate_check(df, URL):
    partial_df = df[df.URL==URL].copy()
    if partial_df.filter_keywords.duplicated().sum()>0:
        return True
    else:
        return False

def total_check(df, URL):
    if (not duplicate_check(df, url)) and size_check(df, url):
          print(url+" ok")
    else:
        print(url+" NOT ok")      

for url in urls:    
    total_check(df, 'URL')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    相关资源
    最近更新 更多