涉及两个DataFrame的计算

时间:2016-05-30 17:27:01

标签: python pandas merge

我有两个DataFrame

DF1:

   mat  inv 
0  100   23  
1  101   35  
2  102  110  

DF2:

   mat  sale
0  100   45
1  101  100
2  102   90

我合并了DataFrame中的df

   mat  inv  sale
0  100   23   45
1  101   35  100
2  102  110   90

所以我可以创建另一个列days

df['days'] = df.inv / df.sale * 30

然后我删除了列sale,并将其作为结果:

DF:

   mat  inv  days
0  100   23   15
1  101   35   10
2  102  110   36

我可以直接在days创建df1列,而无需先合并DataFrame吗?因为我不需要df2的列,只需要执行days操作的值,我真的不想将它们合并以最终删除它。

3 个答案:

答案 0 :(得分:2)

如果确保mat列正确对齐,则可以直接创建新列:

df1 = df1.set_index('mat')
df2 = df2.set_index('mat')
df2['days'] = df1.inv.div(df2.sale).mul(30)

     sale     days
mat                 
100     4    15.33
101   100    10.50
102    90    36.67

答案 1 :(得分:1)

你也可以这样做:

select cname from
(
   select count(medication.id) as total, company.cname 
   from medication
   join company on medication.company_id = company.id
   group by company.cname
   order by count(medication.id) desc
   limit 1
) as t

答案 2 :(得分:0)

肯定df1['days'] = df1['inv'] / df2['sale'] * 30有效吗?