2017-09-01 108 views
0

我试图在通过我的帐户循环时合并或将数据连接到df。大熊猫在循环时合并/将数据合并到数据帧

首先,我成立了由所有月份索引的空数据帧:

Empty DataFrame 
Columns: [] 
Index: [2014-09-30, 2014-09-30, 2014-10-31, 2014-10-31, 2014-11-30, 2014-11-30, 2014-12-31, 2015-01-31, 2015-02-28, 2015-03-31] 

接下来我环槽的所有帐户的值添加到数据帧。

for a in accts: 

     cf = Cashflow.objects.all().filter (id = a.id).order_by ('month').values ('month', 'value') 

     df2 = read_frame (cf) 
     df2 = df2.set_index ('month') 

     df = pd.merge (df2, how = 'left', left_index = True, right_index = True) 

但我在我的输出获得重复数据:

month       
2014-09-30 535400 122928.0 
2014-09-30 535400 122928.0 
2014-10-31 530719 107389.0 
2014-10-31 530719 107389.0 
2014-11-30 512009 97654.0 
2014-11-30 512009 97654.0 
2014-12-31 482277  0.0 
2015-01-31 474815  0.0 

我已经尝试了不同的解决方案。

我可以删除重复的行,但这只是对错误代码的补丁。

这是最好的方法吗?它应该是一个连接而不是一个合并?

回答

1

您在为您开始的空数据库创建的索引中有重复的日期。为什么?

+0

我没有看到重复的日期。啊... – diogenes

+0

.distinct()解决了这个问题。谢谢! – diogenes

1

您的索引中有重复项。

你可以放下他们df.drop_duplicates()