Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.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 是否可以将“first()”和“last()”应用于Pandas中groupby操作中的各个列?_Python_Pandas_Pandas Groupby - Fatal编程技术网

Python 是否可以将“first()”和“last()”应用于Pandas中groupby操作中的各个列?

Python 是否可以将“first()”和“last()”应用于Pandas中groupby操作中的各个列?,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我有一个数据帧: df = pd.DataFrame({'id': [1, 1, 2, 2], 'data': [1, 2, 3, 4], 'value': [10, 9, 8, 7]}) In [4]: df Out[4]: id data value 0 1 1 10 1 1 2 9 2 2 3 8 3 2 4 7 In [5]: df.groupby(['id']).last() Out[

我有一个数据帧:

df = pd.DataFrame({'id': [1, 1, 2, 2], 'data': [1, 2, 3, 4], 'value': [10, 9, 8, 7]})

In [4]: df
Out[4]: 
   id  data  value
0   1     1     10
1   1     2      9
2   2     3      8
3   2     4      7

In [5]: df.groupby(['id']).last()
Out[5]: 
    data  value
id             
1      2      9
2      4      7

In [6]: df.groupby(['id']).first()
Out[6]: 
    data  value
id             
1      1     10
2      3      8

是否可以从应用于
值的
first()
和应用于
数据的
last()
组成的
分组依据生成数据帧?如果这样做更简单,您可以假设
last()
应用于除
value
以外的所有对象,而
first()
仅应用于
value
。我可以在两个单独的GroupBy中完成,但是否可以在一个GroupBy中完成

您可以将功能指令传递给:


如果要在“值”列上调用
first
last
,可以传递函数列表。这里
pandas
可以通过只传递funcs的字符串名来推断调用哪个方法

谢谢!我以前从未使用过
agg
,所以这很好:)
In[80]:
df.groupby('id').agg({'data':'last', 'value':['first','last']})
Out[80]: 
   data value     
   last first last
id                
1     2    10    9
2     4     8    7