熊猫 - 归为零行丢失了几个月
我有一个如下所示的数据框:
产品名称 | 产品类别 | 月 | 销售额 ($) | # 客户 |
---|---|---|---|---|
马铃薯 | 产品 | Jan 2019 | 2 | 1 |
马铃薯 | 产品 | Mar 2019 | 2 | 2 |
马铃薯 | 产品 | Apr 2019 | 1 | 1 |
奶酪 | 乳制品 | Feb 2019 | 1 | 4 |
奶酪 | 乳制品 | Mar 2019 | 3 | 5 |
奶酪 | 乳制品 | Apr 2019 | 3 | 1 |
我希望每个产品都有一行1 月至 5 月之间的每个月,数字列为零:
产品名称 | 产品类别 | 月份 | 销售额 ($) | # 客户 |
---|---|---|---|---|
Potato | Produce | Jan 2019 | 2 | 1 |
Potato | Produce | Feb 2019 | 0 | 0 |
Potato | Produce | Mar 2019 | 2 | 2 |
Potato | Produce | Apr 2019 | 1 | 1 |
Potato | 生产 | 2019 年 5 月 | 0 | 0 |
奶酪 | 乳制品 | 1 月 2019 | 0 | 0 |
奶酪 | 乳制品 | 2 月2019 | 1 | 4 |
奶酪 | 乳制品 | 2019 年 3 月 | 3 | 5 |
奶酪 | 乳制品 | 2019 年 4 月 | 3 | 1 |
奶酪 | 乳制品 | 2019 年 5 月 | 0 | 0 |
我目前的计划是为每个产品选择一个唯一的行,根据需要将其复制几个月,迭代行设置月份和数字列,最后附加这些行。然而,在 pandas 中迭代很少是正确的方法,所以我正在寻找更好的方法。有什么想法吗?
I have a dataframe that looks like this:
Product Name | Product Category | Month | Sales ($) | # Customers |
---|---|---|---|---|
Potato | Produce | Jan 2019 | 2 | 1 |
Potato | Produce | Mar 2019 | 2 | 2 |
Potato | Produce | Apr 2019 | 1 | 1 |
Cheese | Dairy | Feb 2019 | 1 | 4 |
Cheese | Dairy | Mar 2019 | 3 | 5 |
Cheese | Dairy | Apr 2019 | 3 | 1 |
I want each product to have a row for each month between Jan and May, with zero for the numeric columns:
Product Name | Product Category | Month | Sales ($) | # Customers |
---|---|---|---|---|
Potato | Produce | Jan 2019 | 2 | 1 |
Potato | Produce | Feb 2019 | 0 | 0 |
Potato | Produce | Mar 2019 | 2 | 2 |
Potato | Produce | Apr 2019 | 1 | 1 |
Potato | Produce | May 2019 | 0 | 0 |
Cheese | Dairy | Jan 2019 | 0 | 0 |
Cheese | Dairy | Feb 2019 | 1 | 4 |
Cheese | Dairy | Mar 2019 | 3 | 5 |
Cheese | Dairy | Apr 2019 | 3 | 1 |
Cheese | Dairy | May 2019 | 0 | 0 |
My current plan to do this is to select a unique row for each product, duplicate it for as many months as needed, iterate over the rows setting the month and numeric columns, and finally append those rows. However iterating in pandas is rarely the right approach so I am looking for a better way. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论