python - 索引操作 (.loc) ([ ]) 和 (.) 有什么区别

标签 python pandas

让我们以下面这个数据框为例:

df = pd.DataFrame({
    'a':[1,2,3,4],
    'b':[2,4,6,8],
    'c':[True,True,False,False]
    })

>df
   a  b      c
0  1  2   True
1  2  4   True
2  3  6  False
3  4  8  False

我有不同的方法来选择列 a,其中列 c 等于 True:

第一种方式:

df.loc[df.c == True, 'a']

第二种方式:

df.loc[df['c'] == True, 'a']

第三种方式:

df.a[df['c'] == True]

所有这些都得到相同的结果:

0    1
1    2
Name: a, dtype: int64

还有其他操作,例如 df.a[df.c == True] 可以做到这一点。 我只是想知道索引操作 (.loc) ([ ]) 和 (.) 之间有什么区别吗?

最佳答案

但是,.a 和 ["a"] 之间的 pandas 没有没有区别(@cricket_007 链接),如此处回答:In a Pandas DataFrame, what's the difference between using squared brackets or dot to 'cal a column?

<小时/>

但是

当您使用 [] 时,您正在传递 True 和 False 值的列表

[df.c]

打印:

[0     True
 1     True
 2    False
 3    False
 Name: c, dtype: bool]

还有:

type([df.c]) #prints 'list'

换句话说,它们是相同的。

df[df.c] 
df[[True,True,False,False]]

这不等于 .loc,一个数据帧函数,考虑到您的示例,它似乎是最快的

%timeit df[df.c].a
1000 loops, best of 3: 437 µs per loop

%timeit df.a[df.c]
1000 loops, best of 3: 387 µs per loop

%timeit df.loc[df.c, 'a'] #equal to df.loc[df["c"], "a"]
1000 loops, best of 3: 210 µs per loop

关于python - 索引操作 (.loc) ([ ]) 和 (.) 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352714/

相关文章:

python - 从另一个线程更新QLabel的内容时,GIF不会进行动画处理

python - Pandas 映射到新列 SettingWithCopyWarning

python - 如何有条件地更改相邻行的列值?

python - 将 scikit-learn (sklearn) 预测添加到 pandas 数据框

python - 带有条件 python 的部分 fillna

python - 使用不同的顺序按多个键排序

python - 简单的 Python 正则表达式查找模式

PHP "Cancel"代码行

python - 如何从 pytest 回溯中删除库代码调用?

python-2.7 - 从大型数据库查询填充 Pandas 数据框的值 (Python)