【发布时间】:2019-06-18 00:05:50
【问题描述】:
假设我需要一个过滤器的“起始点”。如何将列中所有值的布尔索引设为“真”?
最小的例子: -> 很明显。如果我有一个形状为 (2, 2) 的 df,我想获得一个 (2,1) = True 的布尔索引。当然 2 行是可变的,列的数量也是可变的。
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
现在我有一个条件,比如“col1 中的值需要为 1”,所以我这样做了:
boolean_index = df.loc[:,'col1']==1
返回
0 True
1 False
Name: col1, dtype: bool
但我想要的是不指定任何条件(例如,不指定 boolean_index = df.loc[:,'col1']==1)并返回
0 True
1 True
Name: col1, dtype: bool
我可能只是愚蠢地想出来?还是没有人问过这个问题?
【问题讨论】:
-
有趣的是人们对如此明显的问题投反对票。但是,是的,这是最小的例子: import pandas as pd d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) 布尔索引应该是例如index:[True, True] 因为还没有添加任何选择。
-
"a boolean index of all values"是每一行都设置为true(选择是
-
有趣的方法。但是,返回包含 4 行而不是 2 行 :( pd.Series([True]*df.size, name='col1') 0 True 1 True 2 True 3 True Name: col1, dtype: bool
-
是的,我的错。你肯定知道如何获取
df中的行数并修复它。 -
pd.Series([True]*df.shape[0], name='col1') 有点……不是吗?