嗨,我有一个 python pandas 数据框,我想在其中查看 3 个索引列(电话类型、内存和品牌)的最新 2 个日期(如果可用)之间的变化。数据框如下所示:
"""
“我想了解每个品牌、内存和手机类型的客户持有量的最新变化。因此结果将是(按最新变化排序 - 如果可用):
"""
这意味着,iphone1/32go/apple 的持有量变化是 17/10/19,减少了 0.11 (-0.11),iphone2/32g0/apple 的最后一次变化是在 19/03/ 19,下降了-.09(-0.09),iphone3/64g0/apple最后一次变化是在05/12/16,下降了0.12(-0.12)。因此,当第二行存在时,基本上用第二行减去第一行(意味着 2 条记录包含具有不同日期的相同电话类型/内存/品牌)。如果第二行没有退出,只显示第一行不变(第一行 [customer_holders]-0)。
iphone4 32go Apple -0.50 01/11/2019
我不知道如何用熊猫来做到这一点,而不遍历行......任何帮助都会非常有用。谢谢
原始数据如下:
phonetype memory Brand customers_holders position_date
iphone1 32go Apple 0.77 17/10/2019
iphone1 32go Apple 0.88 10/10/2019
iphone1 32go Apple 0.98 26/09/2019
iphone1 32go Apple 1 15/08/2019
iphone1 32go Apple 0.9 06/08/2019
iphone1 32go Apple 0.8 18/07/2019
iphone1 32go Apple 0.8 18/07/2019
iphone1 32go Apple 0.74 20/06/2019
iphone1 32go Apple 0.61 11/06/2019
iphone1 32go Apple 0.5 21/05/2019
iphone2 32go Apple 0.5 19/03/2019
iphone2 32go Apple 0.59 16/01/2019
iphone2 32go Apple 0.68 04/12/2018
iphone3 64go Apple 0.5 05/12/2016
iphone3 64go Apple 0.62 11/11/2016
iphone3 64go Apple 0.79 12/11/2018
iphone4 32go Apple 0.50 01/11/2019
你可以试试这个:
首先,将日期列更改为datetime
for类型以查找最新日期。
df['position_date'] = pd.to_datetime(df['position_date'], format='%d/%m/%Y')
print(df.head(10))
phonetype memory Brand customers_holders position_date
0 iphone1 32go Apple 0.77 2019-10-17
1 iphone1 32go Apple 0.88 2019-10-10
2 iphone1 32go Apple 0.98 2019-09-26
3 iphone1 32go Apple 1.00 2019-08-15
4 iphone1 32go Apple 0.90 2019-08-06
5 iphone1 32go Apple 0.80 2019-07-18
6 iphone1 32go Apple 0.80 2019-07-18
7 iphone1 32go Apple 0.74 2019-06-20
8 iphone1 32go Apple 0.61 2019-06-11
9 iphone1 32go Apple 0.50 2019-05-21
然后
1. 对关键列和日期列按降序排序。
2. 使用pd.groupby.diff
函数,按组计算与前一行的差值。参考这里!
3.我认为你只需要最近日期和上一个日期之间的差异,所以使用drop_duplicates
只留下第一行。
像这样:
然后,如果 diff 为 nan,您可以添加代码以使用np.where
.
像这样:
key_col = ['phonetype','memory','Brand']
df = df.sort_values(by= key_col + ['position_date'], ascending=False)
df['diff'] = df.groupby(key_col)['customers_holders'].diff(periods=-1)
df = df.drop_duplicates(subset=key_col, keep='first')
# if diff is nan.
df['diff'] = np.where(df['diff'].isnull(), -df['customers_holders'], df['diff'])
print(df)
phonetype memory Brand customers_holders position_date diff
15 iphone3 64go Apple 0.79 2018-11-12 0.29
10 iphone2 32go Apple 0.50 2019-03-19 -0.09
0 iphone1 32go Apple 0.77 2019-10-17 -0.11
让它看起来像你的结果。
df = df.drop('customers_holders', axis=1)\
.rename({'diff':'customers_holders'},axis=1)\
.sort_values(by='phonetype')\
.reset_index(drop=True)
print(df)
phonetype memory Brand position_date customers_holders
0 iphone1 32go Apple 2019-10-17 -0.11
1 iphone2 32go Apple 2019-03-19 -0.09
2 iphone3 64go Apple 2018-11-12 0.29
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句