【问题标题】:Pandas - group and transform with multiple argumentsPandas - 使用多个参数进行分组和转换
【发布时间】:2017-04-06 13:27:42
【问题描述】:

这是我的数据框:

import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'],
                   'B': ['Ar', 'Br', 'Cr', 'Ar', 'Ar'],
                   'C': ['12/15/2011', '11/11/2001', '08/30/2015', '07/3/1999', '03/03/2000'],
                   'D': [1, 7, 3, 4, 5],
                   'F': ['12/1/2011','10/1/2000','8/15/2015','12/1/2011','12/1/2011'] })
df['C'] = pd.to_datetime(df['C'])
df['F'] = pd.to_datetime(df['F'])

我想按列B 分组,然后为每个组检查列C 是否包含列F 30 天内的日期。我会取回整个组的指标列,看起来应该像

df['indicator'] = [1,0,1,1,1]

这是我尝试过的:

def date_test(x, y):

    result = False
    for i in x.index:
        if x[i]<y[i]+ pd.Timedelta(days=30):
            result = True

    return result

df['indicator'] = df.groupby('B')['C','F'].transform(date_test).astype('int64')

但是我回来了TypeError: Transform function invalid for data types

所以我想我不能将两列传递给转换函数。有什么想法吗?

【问题讨论】:

    标签: python pandas group-by transform


    【解决方案1】:

    我认为你是对的,.transform() 的工作方式是传递的函数分别评估每一列(在本例中为 C 和 F)。详情请见here

    但是,我认为您可以使用 .apply() 并获得您想要的结果:

    >>> dfGroup = df.groupby('B')
    >>> dfGroup.apply(lambda x: x['C'] < x['F'] + pd.Timedelta(days=30))
    >>> B    
        Ar  0     True
            3     True
            4     True
        Br  1    False
        Cr  2     True
        dtype: bool
    

    【讨论】:

    • 并分配:df['indicator'] = df.groupby('B').apply(date_test).swaplevel().reset_index(-1, drop=True)
    • @Boud 感谢您添加评论。似乎以下内容也适用df['indicator'] = df.groupby('B').apply(date_test).reset_index(0, drop=True) 或者我错过了什么
    【解决方案2】:

    我不知道它是否会帮助你,但类似:

    df = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four', 'indicator':[]}
    
    if 'one' in df.values() == True:
        df['indicator'].append(1)
    else:
        df['indicator'].append(0)
    

    然后在for循环中运行它以读取'C'中的所有元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2019-10-12
      • 2017-11-20
      • 2019-07-16
      相关资源
      最近更新 更多