我可以使用或条件删除Pandas中的行吗?

2024-09-25 18:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我有一个包含多个列的数据框架,但真正重要的是称为a和B。 如果列A不包含值X或列B不包含值Y,则必须删除该行

我尝试使用此功能:

def removeRows(df, value):
  
  df.drop(df[ (df['A'] != value) | (df['B'] != value)].index, inplace = True)
  return df



But i got this error: 

A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Tags: the数据功能框架truepandasdfindex
1条回答
网友
1楼 · 发布于 2024-09-25 18:27:56

我建议您添加一个如何使用removeRows的示例,因为它看起来不应该引发此警告。
当使用部分数据帧调用removeRows时,会引发此警告

例如:

import pandas as pd
df = pd.DataFrame({
    "A": [1,2,3,4,5],
    "B": [1,7,8,9,10],
    "C": [1,2,3,4,5]
})
df = removeRows(df.loc[df['C'] > 1], 3)

将发出此警告。 尝试将代码更改为

def removeRows(df, value):
    df = df.loc[(df['A'] != value) | (df['B'] != value)]
    return df

相关问题 更多 >