python - Pandas 数据框获取每组的第一行

标签 python pandas dataframe group-by row

我有一个 Pandas DataFrame,如下所示:

df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
                'value'  : ["first","second","second","first",
                            "second","first","third","fourth",
                            "fifth","second","fifth","first",
                            "first","second","third","fourth","fifth"]})

我想按 ["id","value"] 对其进行分组,并获取每个组的第一行:

        id   value
0        1   first
1        1  second
2        1  second
3        2   first
4        2  second
5        3   first
6        3   third
7        3  fourth
8        3   fifth
9        4  second
10       4   fifth
11       5   first
12       6   first
13       6  second
14       6   third
15       7  fourth
16       7   fifth

预期结果:

    id   value
     1   first
     2   first
     3   first
     4  second
     5  first
     6  first
     7  fourth

我尝试了以下,它只给出了 DataFrame 的第一行。对此的任何帮助表示赞赏。

In [25]: for index, row in df.iterrows():
   ....:     df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0])

最佳答案

>>> df.groupby('id').first()
     value
id        
1    first
2    first
3    first
4   second
5    first
6    first
7   fourth

如果您需要 id 作为列:

>>> df.groupby('id').first().reset_index()
   id   value
0   1   first
1   2   first
2   3   first
3   4  second
4   5   first
5   6   first
6   7  fourth

要获取 n 条第一条记录,可以使用 head():

>>> df.groupby('id').head(2).reset_index(drop=True)
    id   value
0    1   first
1    1  second
2    2   first
3    2  second
4    3   first
5    3   third
6    4  second
7    4   fifth
8    5   first
9    6   first
10   6  second
11   7  fourth
12   7   fifth

关于python - Pandas 数据框获取每组的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20067636/

相关文章:

python - Pandas :如何识别具有 dtype 对象但混合类型项目的列?

Python - Pandas - 将特定函数应用于给定级别 - 多索引数据帧

r - 将具有 2 列的数据框转换为只有一列

python - 在 GeoPandas 中将 Legend 添加到 Choropleth map

python - 无法使用 flask.g 访问其他函数中的变量

python - 在 Python 中调用 exit() 时,C++ 析构函数中的互斥锁会导致异常

python - Google Calendar API 日期时间格式 python

python - 根据不同 Dataframe 中的多个条件删除 Dataframe 的行

python - 将混合数据转换为分类数据 : dataframe

python - 使用 R 或 python 在坐标系中绘制向量