【问题标题】:Pandas column difference over timePandas 列随时间的差异
【发布时间】:2020-09-26 23:39:57
【问题描述】:

**在底部编辑**

我有一个包含库存数据的数据框,如下所示:

d = {'product': [a, b, a, b, c], 'amount': [1, 2, 3, 5, 2], 'date': [2020-6-6, 2020-6-6, 2020-6-7, 
2020-6-7, 2020-6-7]}
df = pd.DataFrame(data=d)
df
 product  amount  date
0     a     1      2020-6-6
1     b     2      2020-6-6
2     a     3      2020-6-7
3     b     5      2020-6-7
4     c     2      2020-6-7

我想知道每个月的库存差异是多少。输出如下所示:

df
 product   diff   isnew  date
0     a     nan   nan   2020-6-6
1     b     nan   nan   2020-6-6
2     a     2     False 2020-6-7
3     b     3     False 2020-6-7
4     c     2     True  2020-6-7

抱歉,如果我在第一个示例中不清楚,实际上我有很多个月的数据,所以我不只是在研究一个时期与另一个时期的差异。它需要是一个一般情况,它查看月份 n 与 n-1 的差异,然后是 n-1 和 n-2 等等。

在 Pandas 中最好的方法是什么?

【问题讨论】:

  • 为什么第 4 行 diff 等于 2?没有以前的“c”产品。
  • @ScottBoston 我猜c 是上个月没有出现的新产品(isnewTrue)所以上个月的金额是0

标签: python pandas dataframe datetime


【解决方案1】:

我猜这里的关键是找到isnew

# new products by `product`
new_prods = df['date'] != df.date.min()
duplicated = df.duplicated('product')

# first appearance of new products
# or duplicated *old* products
valids = new_prods ^ duplicated
df.loc[valids,'is_new'] = ~ duplicated

# then the difference:
df['diff'] = (df.groupby('product')['amount'].diff()           # normal differences
                  .fillna(df['amount'])         # fill the first value for all product
                  .where(df['is_new'].notna())  # remove the first month
             )

输出:

  product  amount      date is_new  diff
0       a       1  2020-6-6    NaN   NaN
1       b       2  2020-6-6    NaN   NaN
2       a       3  2020-6-7  False   2.0
3       b       5  2020-6-7  False   3.0
4       c       2  2020-6-7   True   2.0

【讨论】:

    【解决方案2】:

    您可以尝试groupby 列产品和diff 列“差异”列的金额。然后将duplicated 用于“isnew”列。

    df['diff'] = df.groupby('product')['amount'].diff()
    df['isnew'] = ~df['product'].duplicated()
    print (df)
      product  amount      date  diff  isnew
    0       a       1  2020-6-6   NaN   True
    1       b       2  2020-6-6   NaN   True
    2       a       3  2020-6-7   2.0  False
    3       b       5  2020-6-7   3.0  False
    4       c       2  2020-6-7   NaN   True
    

    【讨论】:

    • @MustardTiger 这种方法与 Quang 的方法类似,应该可以扩展到任意月数。这个方法用了好几个月有什么问题?
    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2016-09-08
    • 2021-11-08
    相关资源
    最近更新 更多