提问人:Andy L. 提问时间:4/9/2019 最后编辑:Andy L. 更新时间:1/7/2021 访问量:5416
当 as_index=False 时,groupby.first、groupby.nth、groupby.head 之间有什么区别
what is different between groupby.first, groupby.nth, groupby.head when as_index=False
问:
编辑:我在字符串 np.nan
中犯的菜鸟错误,@coldspeed、@温-ben @ALollz指出了。答案非常好,所以我不会删除这个问题来保留这些答案。
原文:
我已经阅读了这个问题/答案 groupby.first() 和 groupby.head(1) 有什么区别?
该答案解释说,差异在于处理价值。但是,当我打电话给 时,他们都选择很好。NaN
groupby
as_index=False
NaN
此外,Pandas 具有与 和 类似的功能groupby.nth
head
first
和有什么不一样?groupby.first(), groupby.nth(0), groupby.head(1)
as_index=False
示例如下:
In [448]: df
Out[448]:
A B
0 1 np.nan
1 1 4
2 1 14
3 2 8
4 2 19
5 2 12
In [449]: df.groupby('A', as_index=False).head(1)
Out[449]:
A B
0 1 np.nan
3 2 8
In [450]: df.groupby('A', as_index=False).first()
Out[450]:
A B
0 1 np.nan
1 2 8
In [451]: df.groupby('A', as_index=False).nth(0)
Out[451]:
A B
0 1 np.nan
3 2 8
我看到'firs()'重置了索引,而其他2个则没有。除此之外,有什么区别吗?
答:
这里是不同的,你需要做 to ,在你原来的 df 中它是 ,转换后,你会看到不同的np.nan
NaN
string
df=df.mask(df=='np.nan')
df.groupby('A', as_index=False).head(1) #df.groupby('A', as_index=False).nth(0)
Out[8]:
A B
0 1 NaN
3 2 8
df.groupby('A', as_index=False).first()
# the reason why first have the index reset,
#since it will have chance select the value from different row within the group,
#when the first item is NaN it will skip it to find the first not null value
#rather than from the same row,
#If still keep the original row index will be misleading.
Out[9]:
A B
0 1 4
1 2 8
评论
主要问题是您可能存储了字符串,而不是真正的 null 值。以下是这三者处理值的方式:'np.nan'
null
示例数据:
import pandas as pd
df = pd.DataFrame({'A': [1,1,2,2,3,3], 'B': [None, '1', np.NaN, '2', 3, 4]})
first
/last
这将返回每个组中的第一个/最后一个非 null 值。奇怪的是,它不会跳过,尽管这可以通过 kwarg 实现。因此,您可以返回最初属于不同行的列的值:None
dropna=True
df.groupby('A', as_index=False).first()
# A B
#0 1 None
#1 2 2
#2 3 3
df.groupby('A', as_index=False).first(dropna=True)
# A B
#0 1 1
#1 2 2
#2 3 3
head(n)
/tail(n)
返回组中的前/后 n 行。值在行内保持绑定。如果给它一个大于行数的值,它将返回该组中的所有行,而不会抱怨:n
df.groupby('A', as_index=False).head(1)
# A B
#0 1 None
#2 2 NaN
#4 3 3
df.groupby('A', as_index=False).head(200)
# A B
#0 1 None
#1 1 1
#2 2 NaN
#3 2 2
#4 3 3
#5 3 4
nth
这将占用该行,因此值再次保持在行内。 与 相同,尽管它们有不同的用途。例如,如果您需要第 0 行和第 2 行,则很难使用 ,但使用 .此外,它比 .nth
.nth(0)
.head(1)
.head()
.nth([0,2])
.head(10)
.nth(list(range(10))))
df.groupby('A', as_index=False).nth(0)
# A B
#0 1 None
#2 2 NaN
#4 3 3
nth
还支持删除具有任何 null 值的行,因此您可以使用它返回没有任何 null 值的第一行,这与.head()
df.groupby('A', as_index=False).nth(0, dropna='any')
# A B
#A
#1 1 1
#2 2 2
#3 3 3
评论
np.nan
评论
first()
pd.read_clipboard()
np.nan
NaN