【问题标题】:How to keep only a certain set of rows by index in a pandas DataFrame with rule如何在带有规则的pandas DataFrame中按索引仅保留一组特定的行
【发布时间】:2021-01-20 09:16:35
【问题描述】:

跟进这个答案How to keep only a certain set of rows by index in a pandas DataFrame 我需要扩展一下:

E. G。我只想保留其索引遵循规则的行。在我的情况下,“01”到“99”。我必须写一个从 01 到 99 的系列来过滤行吗? 或者会是某种正则表达式好吗? gooddf.loc['[0-9]']

【问题讨论】:

    标签: python dataframe


    【解决方案1】:

    在这种情况下,请确保以“^”指定开头,以“$”指定匹配结尾。

    import pandas as pd
    
    gooddf = pd.DataFrame({"K":[2,3,4,6,2]}, index=["01", "101", "98", "201", "032"])
    
    match_in = gooddf.index.str.match("^[0-9]{1,2}$")
    gooddf[match_in]
    

    【讨论】:

      猜你喜欢
      • 2020-02-17
      • 2020-09-12
      • 2023-03-20
      • 2013-09-08
      • 2022-08-23
      • 2016-01-02
      • 2014-07-28
      • 2018-11-06
      • 1970-01-01
      相关资源
      最近更新 更多