Pandas:如何将另一个数据框的列与列相乘?

6

我有两个数据框,都以名为 month 的日期列作为索引。第一个是 df1,有八行。我关心的列是 df['num_percent'],看起来像这样:

2015-02-01    0.071549
2015-03-01    0.070368
2015-04-01    0.069291
2015-05-01    0.068394
2015-06-01    0.067452
2015-07-01    0.066302
2015-08-01    0.065543
2015-09-01    0.064591
Name: num_percent, dtype: float64

第二个数据框有10万行。我关心的列是df2['total_quantity'],一个样例看起来像这样:
2014-11-01    324199
2014-12-01    378443
2015-01-01    367379
2015-02-01    336863
2015-03-01    380268
2015-04-01    386292
2015-05-01    373213
2015-06-01    403343
2015-07-01    414310
2015-08-01    403684
2015-09-01    420922
Name: total_quantity, dtype: int64

我希望在df2中添加一列,该列的值是df2['total_quantity']df1相应月份的值相乘。

我应该如何做到这一点?

如果我尝试:

df2['percent'] = df2['total_quantity'] * df1['num_percent']

我收到了“ValueError: cannot reindex from a duplicate axis”错误信息。 更新:以下是一些数据和代码,可用于复制该问题:
data = {'month': ['2014-01-01', '2014-02-01', '2014-03-01'],
        'num_percent': [0.4, 0.5, 0.6]}
df1 = pd.DataFrame(data)
df1['month'] = pd.to_datetime(df1['month'])
df1 = df1.set_index('month')

data = {'month': ['2014-01-01', '2014-02-01', '2014-03-01', '2014-01-01'],
        'org': ['00K', '00K', '00K', '00L'],
        'total_quantity': [1000, 1000, 2000, 1000]}
df2 = pd.DataFrame(data)
df2['month'] = pd.to_datetime(df2['month'])
df2 = df2.set_index('month')

# Both of these produce ValueError: cannot reindex... 
df2['percent'] = df1['num_percent'] * df2['total_quantity']
df2.loc[df2.index.isin(df1.index), 'percent'] = df2['total_quantity'] * df1['num_percent']

2
你能否发布代码和数据以重现你的错误?这应该很简单,因为它会在索引不对齐的地方产生“NaN”。 - EdChum
@EdChum 抱歉,已经添加了一些。 - Richard
那么这里的期望输出是什么?你的 df2.index 中有重复值,因此出现了错误。当您拥有重复的索引值时,行值也会重复吗? - EdChum
我已经发布了一个方法,基本上你可以使用join函数连接数据框,然后对列进行乘法运算。 - EdChum
1个回答

5
如果您首先join数据框,然后再进行乘法运算:
In [24]:
df3 = df1.join(df2)
df3['percent'] = df3['num_percent'] * df3['total_quantity']
df3

Out[24]:
            num_percent  org  total_quantity  percent
month                                                
2014-01-01          0.4  00K            1000      400
2014-01-01          0.4  00L            1000      400
2014-02-01          0.5  00K            1000      500
2014-03-01          0.6  00K            2000     1200

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接