【问题标题】:Pandas : How to drop a row where column values match with a specific value (all value are list of value)Pandas:如何删除列值与特定值匹配的行(所有值都是值列表)
【发布时间】:2021-12-11 23:52:53
【问题描述】:

我有一个数据框列,其中所有值都采用列表格式(每个列值一个列表,包含一个或多个项目)。

我想删除在这些列表中找到特定字符串的行(列值可以是 5 项列表,如果其中一项与特定字符串匹配,则必须删除该行)

for row in df:
    for count, item in enumerate(df["prescript"]):
        for element in item:
            if "complementary" in element:
                df.drop(row)

df["prescript"] 是我要迭代的列
"complementary":如果在列值中找到该单词,则行必须放弃

如何改进上面的代码以使其正常工作?

谢谢大家

【问题讨论】:

    标签: python pandas list dataframe drop


    【解决方案1】:

    只需首先使用 Series.apply 屏蔽包含该单词的行

    word = "complementary"
    word_is_in = df["prescript"].apply(lambda list_item: word in list_item)
    

    然后使用布尔索引通过反转布尔系列word_is_in来仅选择不包含该单词的行

    df = df[~word_is_in]
    

    【讨论】:

      【解决方案2】:

      可能引发一些新学习的不切实际的解决方案:

      df = pd.DataFrame(
          columns="   index    drug                 prescript ".split(),
          data= [
                  [       0,      1,     ['a', 's', 'd', 'f'], ],
                  [       1,      2,     ['e', 'a', 'e', 'f'], ],
                  [       2,      3,               ['e', 'a'], ],
                  [       3,      4,   ['a', 'complementary'], ],]).set_index("index", drop=True)
      
      df.loc[
          df['prescript'].explode().replace({'complementary': np.nan}).groupby(level=0).agg(lambda x: ~pd.isnull(x).any())
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-08
        • 1970-01-01
        • 2020-07-06
        • 1970-01-01
        • 2021-02-20
        • 1970-01-01
        • 2022-12-09
        • 2022-01-12
        相关资源
        最近更新 更多