【问题标题】:Divide two dataframes with python用python划分两个数据框
【发布时间】:2016-09-12 16:08:44
【问题描述】:

我有两个数据框:df1df2

df1

TIMESTAMP           eq1 eq2 eq3
2016-05-10 13:20:00  40  30  10
2016-05-10 13:40:00  40  10  20

df2

TIMESTAMP           eq1 eq2 eq3
2016-05-10 13:20:00  10  20  30
2016-05-10 13:40:00  10  20  20

我想将df1 除以df2df1 的每一列除以df2 的所有列,得到这个结果df3

TIMESTAMP           eq1        eq2        eq3
2016-05-10 13:20:00  40/(10+10) 30/(20+20) 10/(30+20)
2016-05-10 13:40:00  40/(10+10) 10/(20+20) 20/(30+20)

有什么想法吗?

【问题讨论】:

    标签: python pandas dataframe multiple-columns division


    【解决方案1】:

    您可以使用div,但在set_index 之前来自两列TIMESTAMP

    df1.set_index('TIMESTAMP', inplace=True)
    df2.set_index('TIMESTAMP', inplace=True)
    
    print (df1.div(df2).reset_index())
                TIMESTAMP  eq1  eq2       eq3
    0 2016-05-10 13:20:00  4.0  1.5  0.333333
    1 2016-05-10 13:40:00  4.0  0.5  1.000000
    

    通过评论编辑:

    df1.set_index('TIMESTAMP', inplace=True)
    df2.set_index('TIMESTAMP', inplace=True)
    print (df2.sum())
    eq1    20
    eq2    40
    eq3    50
    dtype: int64
    
    print (df1.div(df2.sum()).reset_index())
                TIMESTAMP  eq1   eq2  eq3
    0 2016-05-10 13:20:00  2.0  0.75  0.2
    1 2016-05-10 13:40:00  2.0  0.25  0.4
    

    【讨论】:

    • 是的,我假设TIMESTAMP 是索引。
    • 是的,如果第一列是indexes,解决方案更简单df3 = df1.div(df2)
    • @jezrael 谢谢你的回复,但我犯了一个错误,你能检查我的帖子编辑吗?谢谢
    【解决方案2】:

    如果TIMESTAMP 不是索引,这应该可以工作:

    >>> df1.set_index('TIMESTAMP').div(df2.set_index('TIMESTAMP').sum()) 
                         eq1   eq2  eq3
    TIMESTAMP                          
    2016-05-10 13:20:00    2  0.75  0.2
    2016-05-10 13:40:00    2  0.25  0.4
    

    如果TIMESTAMP 是索引,那么简单地说:

    df1.div(df2.sum()) 
    

    【讨论】:

    • 谢谢亚历山大,但我犯了一个错误,你能检查我的帖子编辑吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 2016-12-31
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多