问题:根据“未进入”条件从数据框中删除行[重复]

当日期列的值在日期列表中时,我想从熊猫数据框中删除行。以下代码不起作用:

a=['2015-01-01' , '2015-02-01']

df=df[df.datecolumn not in a]

我收到以下错误:

ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。

I want to drop rows from a pandas dataframe when the value of the date column is in a list of dates. The following code doesn’t work:

a=['2015-01-01' , '2015-02-01']

df=df[df.datecolumn not in a]

I get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().


回答 0

您可以使用pandas.Dataframe.isin

pandas.Dateframe.isin将返回布尔值,具体取决于每个元素是否在列表内a。然后,您~可以将转换TrueFalse,反之亦然。

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

回答 1

您可以使用Series.isin

df = df[~df.datecolumn.isin(a)]

虽然错误消息提示您可以使用all()any(),但仅当您要将结果简化为单个布尔值时,它们才有用。但是,这不是您现在要尝试的操作,而是要针对外部列表测试Series中每个值的成员资格,并保持结果不变(即布尔系列,该布尔系列随后将用于切片原始DataFrame) )。

您可以在Gotchas中阅读有关此内容的更多信息。

You can use Series.isin:

df = df[~df.datecolumn.isin(a)]

While the error message suggests that all() or any() can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).

You can read more about this in the Gotchas.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。