Remove all rows in a Pandas DataFrame where a column is True.

huangapple go评论72阅读模式
英文:

Remove all rows in a Pandas DataFrame where a column is True

问题

以下是翻译好的部分:

我尝试从Pandas数据帧中筛选值,但已经谷歌搜索和使用ChatGPT无果:

为什么

    x1 = df[df!=True]
    x2 = df[df==True]

会导致得到两个数据帧,每个都与原始数据帧具有相同的形状?如何筛选出这个数据帧中为True和不为True的部分?

最终,我想在具有多列的数据帧上进行这种筛选,所以我真正想做的更像是:

    x1 = df[df['col1']!=True]
    x2 = df[df['col1']==True]

希望这有助于您理解问题的翻译。如果您需要进一步的帮助,请告诉我。

英文:

I'm attempting to filter values out of a Pandas dataframe, but have Googled and ChatGPT'd to no avail:

why does

x1 = df[df!=True]
x2 = df[df==True]

result in 2 dataframes, each with the same shape as the original? How can I filter this dataframe into the parts that are True and those that are not.?

Ultimately, I want to do this filtering on a dataframe with several columns, so what I really want to do is more lke:

x1 = df[df['col1']!=True]
x2 = df[df['col1']==True]

答案1

得分: 1

以下是已翻译的部分:

"Take an example like this:" -> "以这个示例为例:"
"To filter to the rows where column 'A' == True" -> "筛选出列 'A' 等于 True 的行"

英文:

Take an example like this:

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
>>> df
   A  B
0  1  4
1  2  5
2  3  6

# df!=True checks for each value in the DataFrame if the value is equal to True (it matches on 1 because 1 is equivalent to True (and False equivalent to 0) when using "==" and "!="
>>> df!=True 
       A     B
0  False  True
1   True  True
2   True  True

# df[df!=True] gets the values which are True in df!=True, and doesn't get anything for the ones which are false (hence A0 being NaN)
>>> df[df!=True]
     A  B
0  NaN  4
1  2.0  5
2  3.0  6

# this is similar to example #1, but only looks at column 'A'
>>> df['A']!=True
0    False
1     True
2     True
Name: A, dtype: bool

To filter to the rows where column 'A' == True

>>> df[df['A']!=True]
   A  B
1  2  5
2  3  6

Pandas interpets this as you wanting to filter the rows, so it takes the values from the previous example, and filters the rows to the ones which return True. If you only want the values which are actually True (i.e. don't match on 1s), you can use is, as in

1 is True # False

huangapple
  • 本文由 发表于 2023年6月29日 09:08:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定