简体   繁体   中英

compare two dataframes and create another

I want to compare two data frames and put a boolean value in other data frame if the value of a is greater or not than the value of b.

Dataframe A:

                   AA        AAPL          FB         GOOG        TSLA        XOM
    Date                                                                             
    2018-01-02  55.169998  168.987320  181.419998  1065.000000  320.529999  80.749893
    2018-01-03  54.500000  168.957886  184.669998  1082.479980  317.250000  82.335831
    2018-01-04  54.700001  169.742706  184.330002  1086.400024  314.619995  82.449791
    2018-01-05  54.090000  171.675278  186.850006  1102.229980  316.579987  82.383316
    2018-01-08  55.000000  171.037628  188.279999  1106.939941  336.410004  82.753677

Dataframe B:
                   AA        AAPL          FB         GOOG        TSLA        XOM
    Date   
    2018-11-15  38.5328  215.266614  155.709600  1119.715189  300.053598  80.719426
    2018-11-16  38.4318  214.728909  155.239400  1117.648390  301.874999  80.678900
    2018-11-19  38.2614  214.097401  154.586801  1114.755590  303.234399  80.645867
    2018-11-20  38.0976  213.179504  153.916600  1111.723590  304.595398  80.545809
    2018-11-21  37.9132  212.312794  153.373000  1109.219391  305.548398  80.452133

So I want to do a dataframe C: fill with zeros and ones. try this:

df = df.where(data.values > sma20.values, 1, 0)

If same number of rows and number of columns convert boolean mask to integers for True/False to 1/0 mapping:

df = pd.DataFrame(data.values > sma20.values).astype(int))

Or use np.where :

df = pd.DataFrame(np.where(data.values > sma20.values, 1, 0))

Also is possible set new columns or index names (or both):

df = pd.DataFrame(data.values > sma20.values).astype(int), 
                  index=data.index, columns=data.columns)

df = pd.DataFrame(np.where(data.values > sma20.values, 1, 0),
                  index=sma20.index, columns=sma20.columns)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM