python - 如何根据日期和两列的组合将缺失的行添加到 pandas DataFrame?
问题描述
我有一个场景,其中我有一个包含 4 列的数据框:
date, product, store, sales_amt
1/1/2019, A,A,200
1/1/2019,A,B,120
1/2/2019, A,A,75
1/3/2019,A,A,69
1/3/2019,A,B,23
--
--
--
1/31/2019,A,B,49
这些日期应该跨越一整个月(例如,在本例中为 2019 年 1 月),但数据框中缺少一些日期。
有没有人有关于 Python 代码的任何提示,可以遍历特定月份的日期并向数据框中添加缺少date
, product
/store
组合且 asales_amt
为零的新行?
product
例如,2019 年 1 月 2 日 A/B 的/store
组合没有条目。
最后的目标是为每个product
/store
组合在该月的每一天都有一个条目。
我怎样才能做到这一点?
解决方案
使用resample
后set_index
:
#create a dummy dataframe with data every other day
s=pd.date_range('2019-01-01', '2019-05-01', freq='2D')
df = pd.DataFrame({'Date':s, 'sales_amt':np.random.randint(100,1000,61)})
df.set_index('Date').resample('D').asfreq().fillna(0)
输出:
sales_amt
Date
2019-01-01 996.0
2019-01-02 0.0
2019-01-03 236.0
2019-01-04 0.0
2019-01-05 225.0
... ...
2019-04-27 444.0
2019-04-28 0.0
2019-04-29 756.0
2019-04-30 0.0
2019-05-01 641.0
推荐阅读
- css - 背景动画忽略FF中的边框半径
- php - 错误:此路由不支持 POST 方法。支持的方法:GET、HEAD。- 使用 laravel livewire
- rdf - 在 RDF N-Triples 中使用 IRI
- flutter - Flutter:自动完成建议显示“对象实例”而不是名称
- visual-studio - AzureDevops:我可以在不发布构建的情况下运行 Vs 自动化测试吗
- text - 如何使用 tshark 将 pcap 文件保存到文本文件
- python - 如何修复此 Python Cv2Error
- typescript - 这个运算符是什么意思 !!~ 在 Typescript 中?
- mapbox-android - MapBox 1.5.1 NavigationView 样式
- bash - awk launchctl 输出和管道到另一个命令