将某些列除以 pandas 中的另一列 [英] Divide certain columns by another column in pandas

查看:79
本文介绍了将某些列除以 pandas 中的另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有更有效的方法将多个列划分为一个特定的列.例如说我有:

Was wondering if there is a more efficient way of dividing multiple columns a certain column. For example say I have:

prev    open    close   volume
20.77   20.87   19.87   962816
19.87   19.89   19.56   668076
19.56   19.96   20.1    578987
20.1    20.4    20.53   418597

我想得到:

prev    open    close   volume
20.77   1.0048  0.9567  962816
19.87   1.0010  0.9844  668076
19.56   1.0204  1.0276  578987
20.1    1.0149  1.0214  418597

基本上,"open"和"close"列已除以"prev"列中的值.

Basically, columns 'open' and 'close' have been divided by the value from column 'prev.'

我能够做到

df['open'] = list(map(lambda x,y: x/y, df['open'],df['prev']))
df['close'] = list(map(lambda x,y: x/y, df['close'],df['prev']))

我想知道是否有更简单的方法?尤其是如果仍然有10列要被相同值除以?

I was wondering if there is a simpler way? Especially if there are like 10 columns to be divided by the same value anyways?

推荐答案

df2[['open','close']] = df2[['open','close']].div(df2['prev'].values,axis=0)

输出:

    prev      open     close  volume
0  20.77  1.004815  0.956668  962816
1  19.87  1.001007  0.984399  668076
2  19.56  1.020450  1.027607  578987
3  20.10  1.014925  1.021393  418597

这篇关于将某些列除以 pandas 中的另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆