使用pandas在Python中查找每个客户最近的两个日期
我有一个熊猫数据框,上面有每个客户的购买日期。我想找出每个唯一客户的最新购买日期和第二个最新购买日期。这是我的数据框:使用pandas在Python中查找每个客户最近的两个日期,python,pandas,Python,Pandas,我有一个熊猫数据框,上面有每个客户的购买日期。我想找出每个唯一客户的最新购买日期和第二个最新购买日期。这是我的数据框: name date ab1 6/1/18 ab1 6/2/18 ab1 6/3/18 ab1 6/4/18 ab2 6/8/18 ab2 6/9/18 ab3 6/23/18 我期望得到以下结果: name second most recent d
name date
ab1 6/1/18
ab1 6/2/18
ab1 6/3/18
ab1 6/4/18
ab2 6/8/18
ab2 6/9/18
ab3 6/23/18
我期望得到以下结果:
name second most recent date most recent date
ab1 6/3/18 6/4/18
ab2 6/8/18 6/9/18
ab3 6/23/18 6/23/18
我知道
data['date'].max()
可以给出最近的购买日期,但我不知道如何找到第二个最近的日期。非常感谢您的帮助。要获取每位客户最近的两个购买日期,您可以先按日期降序排列数据框,然后按名称分组,并将聚合日期转换为单独的列。最后,只需查看这些列中的前两列,就可以得到每个客户最近的两个购买日期
下面是一个例子:
import pandas as pd
# set up data from your example
df = pd.DataFrame({
"name": ["ab1", "ab1", "ab1", "ab1", "ab2", "ab2", "ab3"],
"date": ["6/1/18", "6/2/18", "6/3/18", "6/4/18", "6/8/18", "6/9/18", "6/23/18"]
})
# create column of datetimes (for sorting reverse-chronologically)
df["datetime"] = pd.to_datetime(df.date)
# group by name and convert dates into individual columns
grouped_df = df.sort_values(
"datetime", ascending=False
).groupby("name")["date"].apply(list).apply(pd.Series).reset_index()
# truncate and rename columns
grouped_df = grouped_df[["name", 0, 1]]
grouped_df.columns = ["name", "most_recent", "second_most_recent"]
用grouped_df
结尾这样:
name most_recent second_most_recent
0 ab1 6/4/18 6/3/18
1 ab2 6/9/18 6/8/18
2 ab3 6/23/18 NaN
如果要用相应的most\u recent
值填充任何缺少的second\u most\u recent
值,可以使用np.where
。像这样:
import numpy as np
grouped_df["second_most_recent"] = np.where(
grouped_df.second_most_recent.isna(),
grouped_df.most_recent,
grouped_df.second_most_recent
)
结果:
name most_recent second_most_recent
0 ab1 6/4/18 6/3/18
1 ab2 6/9/18 6/8/18
2 ab3 6/23/18 6/23/18
要获取每个客户最近的两个购买日期,您可以首先按日期降序排列数据框,然后按名称分组,并将聚合的日期转换为单独的列。最后,只需查看这些列中的前两列,就可以得到每个客户最近的两个购买日期 下面是一个例子:
import pandas as pd
# set up data from your example
df = pd.DataFrame({
"name": ["ab1", "ab1", "ab1", "ab1", "ab2", "ab2", "ab3"],
"date": ["6/1/18", "6/2/18", "6/3/18", "6/4/18", "6/8/18", "6/9/18", "6/23/18"]
})
# create column of datetimes (for sorting reverse-chronologically)
df["datetime"] = pd.to_datetime(df.date)
# group by name and convert dates into individual columns
grouped_df = df.sort_values(
"datetime", ascending=False
).groupby("name")["date"].apply(list).apply(pd.Series).reset_index()
# truncate and rename columns
grouped_df = grouped_df[["name", 0, 1]]
grouped_df.columns = ["name", "most_recent", "second_most_recent"]
用grouped_df
结尾这样:
name most_recent second_most_recent
0 ab1 6/4/18 6/3/18
1 ab2 6/9/18 6/8/18
2 ab3 6/23/18 NaN
如果要用相应的most\u recent
值填充任何缺少的second\u most\u recent
值,可以使用np.where
。像这样:
import numpy as np
grouped_df["second_most_recent"] = np.where(
grouped_df.second_most_recent.isna(),
grouped_df.most_recent,
grouped_df.second_most_recent
)
结果:
name most_recent second_most_recent
0 ab1 6/4/18 6/3/18
1 ab2 6/9/18 6/8/18
2 ab3 6/23/18 6/23/18