Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用熊猫如何获得一组中最后两行的平均值_Python_Pandas - Fatal编程技术网

Python 使用熊猫如何获得一组中最后两行的平均值

Python 使用熊猫如何获得一组中最后两行的平均值,python,pandas,Python,Pandas,下面提到的代码似乎有效。 对已排序的组调用tail函数可以得到组的最后n行。 这是否是一个组的tail函数的记录行为。pandas文档中没有提到这一点,我担心在下一个版本中,这种行为可能会改变。 还有其他一些方法可以做到以下几点。对于大型数据集,使用apply函数似乎非常慢。 0.7.3中使用的熊猫版本 df1=pds.DataFrame({'A' : ['CU','CU','CU','CU','CU','AU','AU','AU','AU','AU'],'B':[1,2,3,4,5,1,2,3

下面提到的代码似乎有效。 对已排序的组调用
tail
函数可以得到组的最后n行。 这是否是一个组的tail函数的记录行为。pandas文档中没有提到这一点,我担心在下一个版本中,这种行为可能会改变。 还有其他一些方法可以做到以下几点。对于大型数据集,使用
apply
函数似乎非常慢。 0.7.3中使用的熊猫版本

df1=pds.DataFrame({'A' : ['CU','CU','CU','CU','CU','AU','AU','AU','AU','AU'],'B':[1,2,3,4,5,1,2,3,4,5]}).sort(['A']).reset_index().drop(['index'],axis=1)
df2=df1.groupby(['A'])
df3=df2.tail(2).groupby(['A'])
df3.mean()
文件

对于您的代码,请使用
pivot\u table

a = pds.DataFrame({'A' : ['CU','CU','CU','CU','CU','AU','AU','AU','AU','AU'],
                   'B':[1,2,3,4,5,1,2,3,4,5]}).sort(['A'])

a.pivot_table(rows='A', values='B', aggfunc=lambda x: x.tail(2).mean())
返回

AU    4.5
CU    4.5

本文档仅用于对系列或数据帧使用tail,未提及应用于每个组时tail函数是否返回每个组的最后n行。我认为这里的关键是掌握“拆分应用组合”的诀窍范例——按组执行某项操作与编写函数在整个数据帧上执行该操作相同,然后将其与GroupBy.apply或pivot_表一起使用,如@eumiro所示