使用条件在数据框中创建一个计算列

时间:2019-05-07 03:11:54

标签: python pandas dataframe

我在Python中的数据框具有以下数值数据
mydf =

mydate     mytime                  myopen                 High                   Low                    myclose
---------- ----------------------- ---------------------- ---------------------- ---------------------- -----------
2019-04-15 1900-01-01 15:25:00.000 1675.75                1679.75                1673.35                1673.35
2019-04-15 1900-01-01 15:25:00.000 142.75                 142.8                  142.25                 142.45
2019-04-15 1900-01-01 15:25:00.000 387                    387.5                  385.7                  387.05
2019-04-15 1900-01-01 15:25:00.000 54.7                   54.7                   54.45                  54.45
2019-04-15 1900-01-01 15:25:00.000 1026.1                 1028                   1026.1                 1027.15
2019-04-15 1900-01-01 15:25:00.000 53.65                  53.75                  53.5                   53.7

我需要创建一个称为newcol的计算列,其计算将基于条件。条件是哪个列具有更高的值-myopen / myclose。对于更高的值,我相信 np.fmax 函数适合我的情况。
因此,对于上述df中的每条记录 ...

If myopen >= myclose:
mydf['newcol']= myopen X 6 + 4 * High + (High - myclose)
else:
mydf['newcol']= myclose X 3 + 4 * myclose + (myclose - myopen)

我相信可以通过遍历mydf来达到上述目的, 但是我也觉得应该有更高的效率来完成这项工作。

由于我仍然是新手,希望能为您提供上述帮助。

副词thx

2 个答案:

答案 0 :(得分:3)

除了numpy.where以外,您还可以按条件使用loc函数,如下所示:

df.loc[df.myopen >= df.myclose, 'new_col'] = df.myopen X 6 + 4 * df.High + (df.High - df.myclose)
df.loc[df.myopen < df.myclose, 'new_col'] = df.myclose X 3 + 4 * df.myclose + (df.myclose - df.myopen) 

或者,如果功能变得更复杂,则可以使用dataframe.apply。例如

def open_close_calculation(df):
    if df.myopen >= df.myclose:
        return df.myopen X 6 + 4 * df.High + (df.High - df.myclose)
    else:
        return df.myclose X 3 + 4 * df.myclose + (df.myclose - df.myopen) 

df['new_col'] = df.apply(open_close_calculation, axis=1)

答案 1 :(得分:1)

您可以使用np.where

more_than = ...  # value of new column when more
less_than = ...  # value of new column when less

mydf['newcol'] = np.where(mydf['myopen'] > mydf['myclose'], more_than, less_than)
相关问题