【问题标题】:How to drop specific rows in multiindex dataframe pandas如何删除多索引数据框熊猫中的特定行
【发布时间】:2020-10-18 18:44:56
【问题描述】:

我想删除与 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)

但是执行时间太长了。

【问题讨论】:

  • 显示你的样本数据?

标签: pandas multi-index


【解决方案1】:

看起来你需要按条件选择:

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

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2015-06-13
    • 2020-01-04
    • 2016-09-05
    • 1970-01-01
    • 2023-03-16
    • 2020-01-04
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多