如何在多索引数据框熊猫中删除特定行

时间:2020-06-28 14:36:24

标签: pandas multi-index

我想删除与“技术”部门有关的行,其中alpha矢量值是负数。索引由两部分组成,级别0为“日期”,级别1为“资产”。

                             alpha_vector   sector
date    asset       
2019-06-28 00:00:00+00:00   A     1.218573  Healthcare
                            AA    1.247386  Basic Materials
                            AAL   1.842296  Industrials
                            AAP   -0.713696 Consumer Cyclical
                            AAPL  3.370962  Technology
                            AAXN  -1.892290 Industrials
                            ABB   1.525332  Industrials
                            ABBV  4.647228  Healthcare
                            ABC   1.421925  Healthcare
                            ABMD  3.130564  Healthcare
                            ABT   -6.842299 Healthcare
                            ACAD  -2.015420 Healthcare
                            ACC   0.448264  Real Estate
                            ACGL  -1.179464 Financial Services
                            ACIA  2.839611  Technology

... ... ... ...
2020-06-26 00:00:00+00:00   WRK   5.098169  Consumer Cyclical
                            WSM   -8.620308 Consumer Cyclical
                            WSO   -9.874210 Industrials
                            WST   -10.74130 Healthcare
                            WU    1.267384  Financial Services
                            WWD   3.379096  Industrials
                            WWE   -0.766277 Consumer Cyclical

226296 rows × 2 columns

我已经尝试过了:

for date in df.index.levels[0]:
    for ticker in  df.index.levels[1]:
        if (df.loc[(date,ticker),'sector'] == 'Technology') and (df.loc[(date,ticker),'alpha_vector'] < 0):
            df.drop((date,ticker),inplace =True)

但是执行时间太长。

1 个答案:

答案 0 :(得分:1)

看起来您需要根据条件进行选择:

drop_rows_condition = (df.sector == 'Technology') & (df.alpha_vector < 0)
df = df[ ~drop_rows_condition ]