根据另一列中的日期和标志过滤掉行

时间:2017-09-07 19:02:57

标签: python pandas dataframe group-by pandas-groupby

使用python pandas DataFrame df

Customer | date_transaction_id    | first_flag | dollars
ABC        2015-10-11-123              Y         100
BCD        2015-03-05-872              N         150
BCD        2015-01-01-923              N         -300
ABC        2015-04-04-910              N         -100
ABC        2015-12-12-765              N         -100

上述客户ABC于4月归还房产,然后在11月买了一些东西。在我的分析中,我需要开始计算他们的第一个正面交易作为他们与公司的第一笔交易。如何排除客户ABC的第一笔交易?请注意,客户端BCD不是新客户端,因此不应排除任何行。

那么如何排除first_flag Y之前的日期的交易?

首先,我从date_transaction_id中获取日期并将其格式化为日期字段。

df['date'] = df['date_transaction_id'].astype(str).str[:10]
df['date']= pd.to_datetime(df['date'], format='%Y-%m-%d')

然后我按客户和日期排序

df = df.sort_values(['Customer', 'date'], ascending=[True, False])

但是现在我陷入了困境,如何在first_flag为Y之前按客户端删除行。请注意,在标记为Y的事务之前,客户端可以有一个,没有或多个事务。< / p>

这是我要找的输出:

Customer | date       | first_flag | dollars
ABC        2015-10-11      Y         100
ABC        2015-12-12      N         -100
BCD        2015-01-01      N         -300
BCD        2015-03-05      N         150

5 个答案:

答案 0 :(得分:5)

df 

  Customer date_transaction_id first_flag  dollars
0      ABC      2015-10-11-123          Y      100
1      BCD      2015-03-05-872          N      150
2      BCD      2015-01-01-923          N     -300
3      ABC      2015-04-04-910          N     -100
4      ABC      2015-12-12-765          N     -100

df['date']= pd.to_datetime(df['date_transaction_id']\
                            .astype(str).str[:10], format='%Y-%m-%d')
df = df.sort_values(['Customer', 'date'])\
                            .drop('date_transaction_id', 1)

df 

  Customer first_flag  dollars       date
3      ABC          N     -100 2015-04-04
0      ABC          Y      100 2015-10-11
4      ABC          N     -100 2015-12-12
2      BCD          N     -300 2015-01-01
1      BCD          N      150 2015-03-05

首先用整数值替换first_flag

df.first_flag = df.first_flag.replace({'N' : 0, 'Y' : 1})

现在,groupby Customercumsum max first_flag

df = df.groupby('Customer')[['date', 'first_flag', 'dollars']]\
                .apply(lambda x: x[x.first_flag.cumsum() == x.first_flag.max()])\
                .reset_index(level=0)
df
  Customer       date  first_flag  dollars
0      ABC 2015-10-11           1      100
4      ABC 2015-12-12           0     -100
2      BCD 2015-01-01           0     -300
1      BCD 2015-03-05           0      150

可选:使用

替换旧的Y / N的积分值
df.first_flag = df.first_flag.replace({0 : 'N', 1 : 'Y'})  
df

  Customer       date first_flag  dollars
0      ABC 2015-10-11          Y      100
4      ABC 2015-12-12          N     -100
2      BCD 2015-01-01          N     -300
1      BCD 2015-03-05          N      150

答案 1 :(得分:2)

C:\inetpub\logs\FailedReqLogFiles

答案 2 :(得分:2)

回答您的第一个问题,即排除有标记为“Y”的客户的第一笔交易:

import pandas as pd
df = pd.DataFrame([['ABC','2015-10-11','Y',100],
                  ['BCD','2015-03-05','N',150],
                  ['BCD','2015-01-01','N',-300],
                  ['ABC','2015-04-04','N',-100],
                  ['ABC','2015-12-12','N', -100]], 
                  columns=['Customer','date', 'first_flag','dollars'])

# Extract the original columns
cols = df.columns

# Create a label column of whether the customer has a 'Y' flag
df['is_new'] = df.groupby('Customer')['first_flag'].transform('max')

# Apply the desired function, ie. dropping the first transaction
# to the matching records, drop index columns in the end

new_customers = (df[df['is_new'] == 'Y']
                 .sort_values(by=['Customer','date'])
                 .groupby('Customer',as_index=False)
                 .apply(lambda x: x.iloc[1:]).reset_index()
                 [cols])

# Extract the rest
old_customers = df[df['is_new'] != 'Y']

# Concat the transformed and untouched records together
pd.concat([new_customers, old_customers])[cols]

输出:

Customer | date       | first_flag | dollars
ABC        2015-10-11      Y         100
ABC        2015-12-12      N         -100
BCD        2015-01-01      N         -300
BCD        2015-03-05      N         150

答案 3 :(得分:2)

所有预设与cᴏʟᴅsᴘᴇᴇᴅ的答案相同,在我的回答中,我使用idxmax

预设

df['date']= pd.to_datetime(df['date_transaction_id']\
                            .astype(str).str[:10], format='%Y-%m-%d')
df=df.sort_values(['Customer','date']).replace({'N' : 0, 'Y' : 1}).reset_index(drop=True)
L=df.groupby('Customer')['first_flag'].apply(lambda x : x.index>=x.idxmax()).apply(list).values.tolist()
import functools
L=functools.reduce(lambda x,y: x+y,L)
df[L]


Out[278]: 
  Customer date_transaction_id  first_flag  dollars       date
1      ABC      2015-10-11-123           1      100 2015-10-11
2      ABC      2015-12-12-765           0     -100 2015-12-12
3      BCD      2015-01-01-923           0     -300 2015-01-01
4      BCD      2015-03-05-872           0      150 2015-03-05

答案 4 :(得分:1)

这是一个对groupby对象的每个组进行操作的函数。

def drop_before(obj):
    # Get the date when first_flag == 'Y'
    y_date = obj[obj.first_flag == 'Y'].date
    if not y_date.values:
        # If it doesn't exist, just return the DataFrame
        return obj
    else:
        # Find where your two drop conditions are satisfied
        cond1 = obj.date < y_date[0]
        cond2 = abc.first_flag == 'N'
        to_drop = obj[cond1 & cond2].index
        return obj.drop(to_drop)

res = df.groupby('Customer').apply(drop_before)
res = res.set_index(res.index.get_level_values(1))
print(res)
  Customer date_transaction_id first_flag  dollars       date
4      ABC      2015-12-12-765          N     -100 2015-12-12
0      ABC      2015-10-11-123          Y      100 2015-10-11
1      BCD      2015-03-05-872          N      150 2015-03-05
2      BCD      2015-01-01-923          N     -300 2015-01-01

因此,为客户的每个描绘单独的DataFrame(ABC为1,BCD为1)。然后,当您使用apply时,drop_before将应用于每个子框架,然后重新组合。

这假设每位客户最多只有一个first_flag == 'Y'。你的问题似乎就是这种情况。