gpt4 book ai didi

python - dataframe.series 和 dataframe ['series' ] 有什么区别?

转载 作者:行者123 更新时间:2023-11-28 21:41:00 26 4
gpt4 key购买 nike

我只是尝试对我的数据框进行排序并使用了以下函数:

df[df.count >= df.count.quantile(.95)]

返回错误:

AttributeError: 'function' object has no attribute 'quantile'

但是将系列括起来效果很好:

df[df['count'] >= df['count'].quantile(.95)]

这不是我第一次根据这种区别得到不同的结果,但它通常也不会发生,而且我一直认为这是两个相同的对象。

为什么会这样?

最佳答案

因为 count 是数据框的内置方法之一,当您使用 . 时,它被识别为方法而不是列 count ,即 内置方法优先于列:

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

df.count()
#A 3
#B 3
#count 3
#dtype: int64

df.count
# V V V V V V V V
#<bound method DataFrame.count of A B count
#0 1 2 4
#1 2 3 5
#2 3 4 6>

点和括号之间的另一个区别是,您不能使用点来创建新列。即如果该列不存在,df.column = ... 将不起作用,在这种情况下您必须使用方括号。作为 df[column] = ...,使用上面的虚拟数据框:

# original data frame
df
# A B count
#0 1 2 4
#1 2 3 5
#2 3 4 6

使用点创建新列将不起作用,C 被设置为属性而不是列:

df.C = 2    
df
# A B count
#0 1 2 4
#1 2 3 5
#2 3 4 6

虽然括号是向数据框添加新列的标准方法:

df['C'] = 2
df
# A B count C
#0 1 2 4 2
#1 2 3 5 2
#2 3 4 6 2

如果列已经存在,假设数据框没有同名属性(如上面的count 的情况),用点修改它是有效的:

df.B = 3    
df
# A B count C
#0 1 3 4 2
#1 2 3 5 2
#2 3 3 6 2

关于python - dataframe.series 和 dataframe ['series' ] 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45156053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com