![](/img/trans.png)
[英]How do I combine Pandas dataframes by looking at dates in one dataframe that fall within a date range in another dataframe?
[英]How do I get both the sum and an overlapping a list of dates that fall within a sliding window in a Pandas df?
我有一个这样的df:
日期<\/th> | 名称<\/th> | 数量<\/th><\/tr><\/thead> | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2021-07-01<\/td> | '氯氧'<\/td> | 1<\/td><\/tr> | ||||||||||||
2021-07-14<\/td> | '氯氧'<\/td> | 20<\/td><\/tr> | ||||||||||||
2021-07-29<\/td> | '氯氧'<\/td> | 700<\/td><\/tr> | ||||||||||||
2021-08-11<\/td> | '氯氧'<\/td> | 6000<\/td><\/tr> | ||||||||||||
2021-08-12<\/td> | '苏里南'<\/td> | 3<\/td><\/tr> | ||||||||||||
2021-08-19<\/td> | '苏里南'<\/td> | 10<\/td><\/tr><\/tbody><\/table> 我想要一个月内的金额总和,加上该月范围内的所有日期。 所以像这些结果:
|
使用
pd.to_datetime<\/code><\/a> ,
Series.dt.to_period<\/code><\/a>和
Groupby.agg<\/code><\/a> :
In [874]: df['date'] = pd.to_datetime(df['date']) # Convert date column to pandas datetime
In [923]: res = df.groupby(['name', df['date'].dt.to_period('M')], as_index=False).agg({'amount': sum, 'date': lambda x: list(x.dt.date)})
In [924]: res
Out[924]:
name amount date
0 'Chlorox' 721 [2021-07-01, 2021-07-14, 2021-07-29]
1 'Chlorox' 6000 [2021-08-11]
2 'Suriname' 13 [2021-08-12, 2021-08-19]
我认为目标是根据
month<\/code>和
name<\/code>按列分组。
所以结果数据框将如下所示 -
date amount
name Month
Chlorox 7 2021-07-01, 2021-07-14, 2021-07-29 721
8 2021-08-11 6000
Suriname 8 2021-08-12, 2021-08-19 13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.